0

在我的web应用程序中,applicationContext中有两个数据源bean,一个用于real-env,另一个用于执行测试。 dataSource对象被注入到一个DAO类中。使用Spring配置文件如何配置测试数据源应该在运行时注入DAO Test(JUnit)和real-env dataSource应该注入DAO而代码部署到real-env?使用Spring配置文件向DAO注入特定bean

回答

1

其实有两种方式来实现自己的目标:

  1. 一种方法是使用两个不同的Spring配置文件,一个用于测试(JUnit的),另一个用于运行时(实ENV)。

用于真正的ENV:

<!-- default-spring-config.xml --> 
<beans> 

    ...other beans goes here... 

    <bean id="datasource" class="xx.yy.zz.SomeDataSourceProvider1" /> 

</beans> 

用于测试:

<!-- test-spring-config.xml --> 
<beans> 

    ...other beans goes here... 

    <bean id="datasource" class="xx.yy.zz.SomeDataSourceProvider2" /> 

</beans> 

在web.xml中指定默认弹簧-config.xml中作为contextConfigLocation春季在运行时使用:

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>/WEB-INF/default-spring-config.xml</param-value> 
</context-param> 

最后指定测试 - 弹簧 - config.xml中ContextConfiguration用于测试:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration("/test-spring-config.xml")// it will be loaded from "classpath:/test-spring-config.xml" 
public class YourClassTest { 

    @Autowired 
    private DataSource datasource; 

    @Test 
    public void your_function_test() { 

     //use datasource here... 

    } 
} 

  • 第二种方法是使用Spring型材正如你所建议的那样(即使我更喜欢第一个,因为它对这种情况更合适)。
  • 首先添加这些行到你的web.xml让春天知道默认配置文件(实ENV)的:

    <context-param> 
        <param-name>spring.profiles.active</param-name> 
        <param-value>default</param-value 
    </context-param> 
    

    现在到您的Spring配置文件(一个单一的配置文件)创建两个不同的数据源:

    <beans xmlns="http://www.springframework.org/schema/beans" 
        xsi:schemaLocation="..."> 
    
        ...other beans goes here... 
    
        <beans profile="default"> 
    
         <bean id="defaultDatasource" class="xx.yy.zz.SomeDataSourceProvider1" /> 
    
        </beans> 
    
        <beans profile="test" > 
    
         <bean id="testDatasource" class="xx.yy.zz.SomeDataSourceProvider2" /> 
    
        </beans> 
    
    </beans> 
    

    使用ActiveProfiles然后注入数据源到你的测试类

    @RunWith(SpringJUnit4ClassRunner.class) 
    @ContextConfiguration 
    @ActiveProfiles("test") 
    public class YourClassTest { 
    
        @Autowired 
        private DataSource datasource; 
    
        @Test 
        public void your_function_test() { 
    
         //use datasource here... 
    
        } 
    } 
    

    来源:https://spring.io/blog/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles