Spring Security without web.xml

前端 未结 7 1521
不思量自难忘°
不思量自难忘° 2021-01-30 15:06

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?

7条回答
  •  萌比男神i
    2021-01-30 15:29

    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.

    Using Spring Security without 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.

    Using Spring Security with Spring or Spring MVC

    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 ...
    }
    

提交回复
热议问题