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

    相關問題