Spring MVC在集成测试中混合xml和java @ContextConfiguration

时间:2015-06-02 20:35:41

标签: spring-mvc spring-security spring-test spring-test-mvc spring-mvc-test

我正在尝试使用XML配置和@Configuration带注释的类的组合来配置Spring MVC集成测试。

@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 {
}

正确初始化java配置。问题是虽然在初始化期间找到并解析了"**/security-config.xml"文件但是在WebApplicationContext中从未注册过所有在其中定义的Spring安全bean。

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)

所以我的问题是如何在Spring MVC Integration测试中同时使用基于XML和注释的配置?

我可以将spring security配置更改为基于java / annotated的一个...我宁愿不这样做。我发现使用spring security命名空间比使用java配置更具可读性和简洁性。

另外,请注意,这种组合的XML / Java配置在非测试环境中完美运行。

  • Spring v4.1.6
  • Spring Security v4.0.1

WebApplicationContext配置:

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 {

}

安全-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>

2 个答案:

答案 0 :(得分:0)

更新:经过进一步考虑并根据您的最新反馈,您遇到的行为可能是Spring Framework 4.1.4中引入的错误的结果(请参阅{{ 3}}了解详情)。

尝试降级到Spring Framework 4.1.3,如果您仍然遇到不良行为,请告诉我。

  

请注意,这种组合的XML / Java配置在非测试环境中运行良好。

怎么样?

你真的在生产中的层次结构中加载了三(3)个上下文吗?

我对此表示怀疑。相反,我假设您以某种方式从process.env.USERDOMAIN + '\\' + process.env.USERPROFILE.split('\\').pop()WebApplicationContext加载单个 root "classpath:**/security-config.xml"

因此,最重要的问题是:如何在生产环境中配置根WebApplicationContext?

一旦您回答了这个问题,我就可以告诉您如何在测试配置中实现相同的功能。 ;)

此致

Sam( Spring TestContext Framework的作者

答案 1 :(得分:0)

注意来自PathMatchingResourcePatternResolver的说明:

  

请注意,与Ant样式模式结合使用时,“classpath *:”只能在模式启动之前与至少一个根目录可靠地工作,除非实际目标文件驻留在文件系统中。这意味着像“classpath *:*。xml”这样的模式不会从jar文件的根目录中检索文件,而只能从扩展目录的根目录中检索文件。这源于JDK的ClassLoader.getResources()方法中的限制,该方法仅返回传入的空字符串的文件系统位置(指示搜索的潜在根)。