Spring MVC Mixing xml and java @ContextConfiguration in integration test

I am trying to configure a Spring MVC Integration test using a combination of XML config and @Configuration annotated classes.

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@TestPropertySource({"/spring-security.properties",
                     "/rabbitmq-default.properties",
                     "/mongodb-default.properties",
                     "/webapp-override.properties"})
@ContextHierarchy({
    @ContextConfiguration("classpath:**/security-config.xml"),
    @ContextConfiguration(classes = RootConfig.class),
    @ContextConfiguration(classes = SpringMvcConfig.class)
})
public class BaseConfiguredMvcIntegrationTest {
}

The java configurations are initialized correctly. The problem is although the "**/security-config.xml" file is found and parsed during initialization... all the spring security beans defined in there are never registered in the WebApplicationContext.

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)

So my question is how do you utilize both XML based and annotated based configuration in a Spring MVC Integration test?

I could change the spring security config to java/annotated based one... I would rather not do this. I find using the spring security namespace more readable and concise than using the java config.

Also, note this combined XML/Java configuration works perfectly fine in a non-test environment.

  • Spring v4.1.6
  • Spring Security v4.0.1

WebApplicationContext Config:

package com.gggdw.web.config;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.DispatcherServlet;


@Configuration
public class GGGWebInitializer implements WebApplicationInitializer {

    public static final String SERVLET_NAME = "ggg";

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(RootConfig.class);

        // Manage the lifecycle of the root application context
        servletContext.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
        dispatcherContext.register(SpringMvcConfig.class);

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet(SERVLET_NAME, new DispatcherServlet(dispatcherContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

        //Spring security config
        FilterRegistration.Dynamic springSecurityFilterChain = servletContext.addFilter(
                                                    "securityFilter", new DelegatingFilterProxy("springSecurityFilterChain"));

        springSecurityFilterChain.addMappingForServletNames(null, false, SERVLET_NAME);
        //springSecurityFilterChain.setAsyncSupported(true);

        servletContext.addFilter("hiddenHttpMethodFilter", HiddenHttpMethodFilter.class);

    }

}

RootConfig.class

@Configuration
@Import({WebPropertiesConfig.class,                     // loads all properties files on class path from resources folder
         MongoConfig.class                              // init mongodb connection 
         })                     
@ImportResource({"classpath:**/security-config.xml"})   // spring security xml config (java config not as readable)
public class RootConfig {

}

security-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- <context:property-placeholder location="classpath:spring-security.properties" /> -->

    <security:global-method-security pre-post-annotations="enabled" secured-annotations="enabled">
       <security:expression-handler ref="expressionHandler"/>
    </security:global-method-security>

    <bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
        <property name="permissionEvaluator" ref="permissionEvaluator"/>
    </bean>

    <bean id="permissionEvaluator"
          class="com.my.local.package.security.GenericPermissionEvaluator">
    </bean>

    <!-- Configure Spring Security -->
    <security:http auto-config="true" use-expressions="true" >
        <security:form-login login-page="${spring.security.login-page}" 
                             login-processing-url="${spring.security.login-processing-url}" 
                             default-target-url="${spring.security.default-target-url}" 
                             authentication-failure-url="${spring.security.authentication-failure-url}" 
                             username-parameter="${spring.security.username-parameter}"
                             password-parameter="${spring.security.password-parameter}"
        />
        <security:logout logout-url="${spring.security.logout-url}" 
                 logout-success-url="${spring.security.logout-success-url}" />

        <security:intercept-url pattern="/**" requires-channel="https" />
        <security:intercept-url pattern="/s/**" access="isAuthenticated()" requires-channel="https" />
        <security:custom-filter ref="log4JMDCFilter" after="SECURITY_CONTEXT_FILTER"/>
        <security:access-denied-handler error-page="${spring.security.access-denied-handler-error-page}" />
        <!-- <security:session-management invalid-session-url="${spring.security.invalid-session-url}"/> 
              2 types of invalid session, brand new user and a timeout of a previous logged in user
              both need to be handled differently -->
    </security:http>

    <bean id="customUserDetailsService" class="com.my.local.package.CustomUserDetailsService" depends-on="userRepository"/>   

    <bean id="bCryptPasswordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />


   <!--  log4j filter to add userName and ipAddress into logging on a per request/thread basis -->
    <bean id="log4JMDCFilter" class="com.my.local.package.filter.Log4JMDCFilter"/>

    <security:authentication-manager>
       <security:authentication-provider user-service-ref="customUserDetailsService">
           <security:password-encoder ref="bCryptPasswordEncoder"/>
       </security:authentication-provider>
    </security:authentication-manager>


</beans>

Answers


UPDATE: upon further consideration and based on your latest feedback, the behavior you're experiencing might be the result of a bug that was introduced in Spring Framework 4.1.4 (see SPR-13075 for details).

Try downgrading to Spring Framework 4.1.3, and let me know if you still experience the undesired behavior.


note this combined XML/Java configuration works perfectly fine in a non-test environment.

How so?

Do you literally have three (3) contexts loaded in a hierarchy in production?

I doubt that. Rather, I assume you are somehow loading a single root WebApplicationContext from "classpath:**/security-config.xml" and RootConfig.class.

Thus, the most important question is: How are you configuring the root WebApplicationContext in production?

Once you have answered that, I can tell you how to achieve the same thing in your test configuration. ;)

Regards,

Sam (author of the Spring TestContext Framework)


Pay attention to the note from PathMatchingResourcePatternResolver:

Note that "classpath*:" when combined with Ant-style patterns will only work reliably with at least one root directory before the pattern starts, unless the actual target files reside in the file system. This means that a pattern like "classpath*:*.xml" will not retrieve files from the root of jar files but rather only from the root of expanded directories. This originates from a limitation in the JDK's ClassLoader.getResources() method which only returns file system locations for a passed-in empty String (indicating potential roots to search).


Need Your Help

Double quotes keep getting parsed in PHP's shell_exec and sed

php bash sed

I've spent hours trying to figure this out. I am using shell_exec (yes, I know the security problems associated with this) and sed to change text in a file.