@Configuration
@EnableWebSecurity
public class AppSecurityConfig {
// security configurations...
}However, have you noticed that when you forget to use this annotation, the security of your application still works as expected? Is there something wrong? What’s the truth? You must use this annotation in Java projects that use only the Spring framework (no Spring Boot). Use it to let Spring Security implement some basic configurations for HTTP security, web security and exploit protection. There are no auto configurations in non-Spring Boot projects so you have to specify this annotation in a configuration class. Otherwise, you will have to write quite a lot of code for basic security configurations, which is time-consuming and error-prone.
In Spring Boot projects, it’s optional to use the @EnableWebSecurity annotation because when Spring Security is present in the classpath, the SecurityAutoConfiguration class imports the SpringBootWebSecurityConfiguration class:
...
@Import({ SpringBootWebSecurityConfiguration.class, ... })
public class SecurityAutoConfiguration {
...
}Then the SpringBootWebSecurityConfiguration class adds the @EnableWebSecurity annotation like this:class SpringBootWebSecurityConfiguration {
...
@ConditionalOnClass(EnableWebSecurity.class)
@EnableWebSecurity
static class WebSecurityEnablerConfiguration {
}
}This means Spring Security auto-configuration feature, which is activated by Spring Boot auto-configuration when it finds Spring Security in the classpath, will end up using the @EnableWebSecurity annotation. That’s the reason why you don’t have to use this annotation explicitly in Spring Boot projects. Makes sense now?
In Spring Boot projects, it’s optional to use the @EnableWebSecurity annotation because when Spring Security is present in the classpath, the SecurityAutoConfiguration class imports the SpringBootWebSecurityConfiguration class:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.