How to implement Spring Security 4 with both XML and Java config

喜夏-厌秋 提交于 2019-11-30 21:13:31
logixplayer

Thanks to ArunM, I revisited my issue and now have an XML and Java config combination. Spring MVC and the web app does use web.xml and default-servlet.xml PLUS a java config app class that imports Spring Security.

@Configuration
@Import({ SecurityConfig.class})
@ImportResource( {"classpath:web-context.xml",
   "classpath:service-context.xml","classpath:data-context.xml"})
public class AppConfig {
   public AppConfig() {
      super();
   }
}

I use the @Import annotation to import the Spring Security SecurityConfig class.

I also do my contextConfigLocation scanning for all my context files via annotation: @ImportResource.

The trick was not to load SecurityConfig via the contextConfigLocation BUT create an AppConfig class that sets up the app context by including everything in it together.

Assuming what you want is to get Spring Security Java Config working with only 2 classes SecurityConfig and SecurityWebApplicationInitializer, you need to do the following to get it working. Please note that I am assuming that your spring mvc configuration is still XML. Please note that com.mkyong.web.config package will have the SecurityConfigclass. This will ensure that the web context will have your security configuration available.

Web.xml as follows

<context-param>
          <param-name>contextClass</param-name>
          <param-value>
              org.springframework.web.context.support.AnnotationConfigWebApplicationContext
          </param-value>
      </context-param>
      <context-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>com.mkyong.web.config</param-value>
      </context-param>

   <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

Add the following line in your spring-context.xml:

<!-- to activate annotations in beans already registered in the application context -->
<context:annotation-config />

and then can add the bean definition for the security config.

<bean name="SecurityConfig" class="com.config.security.SecurityConfig" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!