What is the recommended way to add Spring Security to a web application that is using Spring\'s new WebApplicationInitializer
interface instead of the web.xml file?
The Spring Security Reference answers this question and the solution depends on whether or not you are using Spring Security in conjunction with Spring or Spring MVC.
If you are not using Spring Security with Spring or Spring MVC (i.e. you do not have an existing WebApplicationInitializer
) then you need to provide the following additional class:
import org.springframework.security.web.context.*;
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super(SecurityConfig.class);
}
}
Where SecurityConfig
is your Spring Security Java configuration class.
If you are using Spring Security with Spring or Spring MVC (i.e. you have an existing WebApplicationInitializer
) then firstly you need to provide the following additional class:
import org.springframework.security.web.context.*;
public class SecurityWebApplicationInitializer
extends AbstractSecurityWebApplicationInitializer {
}
Then you need to ensure that your Spring Security Java configuration class, SecurityConfig
in this example, is declared in your existing Spring or Spring MVC WebApplicationInitializer
. For example:
import org.springframework.web.servlet.support.*;
public class MvcWebApplicationInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class>[] getRootConfigClasses() {
return new Class[] {SecurityConfig.class};
}
// ... other overrides ...
}