2017-07-10 33 views
0

我想在我的Spring MVC應用程序中引入JUnit,並且我正在使用Java和xml配置(我的java配置使用xml來自動裝入某個變量)的組合來定義我的bean:嵌套的Java和Xml的JUnit彈簧配置

// 1 - 我的測試類

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = MvcConfiguration_Test.class) 
@WebAppConfiguration 
public class ClassTest { 
    @Autowired 
    @Qualifier("databaseTest") 
    DataBaseConn conn; 

    @Test 
    public void test() { 
    // do some stuff 
    } 
} 

// 2 - 爪哇配置

@EnableWebMvc 
@Configuration 
@ImportResource({ "applicationContext.xml" }) // this file is in classpath, actually I'm using "classpath:**/applicationContext.xml" but the next step is to move this file in resources/test :) 
public class MvcConfiguration_Test extends MvcConf{ 

    @Autowired 
    String dbName; // defined in applicationContext.xml 

    @Bean 
    public DataBaseConn databaseTest(){ 
    DataBaseConn conn = new DataBaseConn(); 
    conn.addDataSource(dbName, jndi, user, pwd) 
    return conn; 
    } 
} 

// 3 - xml配置 - applicationContext.xml中

<?xml version="1.0" encoding="UTF-8"?> 
<beans ... 
    <context:annotation-config /> 
    <bean id="dbName" class="java.lang.String"> 
     <constructor-arg value="myDb"/> 
    </bean> 
</beans> 

當我啓動我的JUnit測試,我得到以下錯誤:

java.lang.IllegalStateException: Failed to load ApplicationContext 
... 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcConfiguration_Test': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: java.lang.String package.MvcConfiguration_Test.dbName; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. 

的解決方法是絲骯髒的方式分貝的名字: 字符串DBNAME =「MYDB」; 但這不是所需的解決方案:)

PS。我的MVC應用程序被自動裝配值correclty(我只從MvcConfiguration刪除@ComponentScan("ct.cbi")讀取測試配置

+1

自動裝配字符串bean對我來說似乎很奇怪。我覺得從屬性文件中讀取這個值是更好的方法。這當然不是我以前見過的。 – Plog

回答

2

在春季documention提到你不能自動裝配字符串:

You cannot autowire so-called simple properties such as primitives, Strings, and Classes (and arrays of such simple properties). This limitation is by-design.

我建議什麼是定義在application.properties文件屬性,這樣你就可以外部化這方面的信息。

你應該看看this進一步的信息。

+0

你說得對,但我的問題與此無關。爲了確保這一點,我改變了類型: '@Autowired DbNameBean dbNameBean;' 和在applicationContext.xml中> '<豆ID = 「dbNameBean」 類= 「package.DbNameBean」> \t \t ' 但仍然有同樣的問題。 – NikNik

0

我認爲問題可能是您的applicationContext.xml在測試類路徑中不可見。您需要將其移至測試/資源以使其正常工作。

但是@Rlarroque在他的回答中提到你真的應該考慮一個屬性解決方案來配置你的數據庫名稱。首先,它可以讓你重新配置數據庫名稱,而無需重建整個應用程序。

+0

你是對的:)但在我以正確的方式配置我的環境之前,我需要讓它工作:)正如我在我的問題中所說的,applicationContext.xml位於classpath中。我試圖從classpath中移除文件,異常是:'由於:java.io.FileNotFoundException:無法打開ServletContext資源[/applicationContext.xml]'。不過謝謝你的參與。 – NikNik