/pom.xml
...
<properties>
...
<jdbc.driver>com.mysql.jdbc.Driver</jdbc.driver>
<jdbc.url>jdbc:mysql://${database.host}/${database.name}</jdbc.url>
<jdbc.user>${database.user}</jdbc.user>
<jdbc.password>${database.password}</jdbc.password>
...
</properties>
...
<profiles>
<profile>
<id>dev</id>
<properties>
...
<database.name>database</database.name>
<database.host>localhost</database.host>
<database.user>root</database.user>
<database.password></database.password>
...
</properties>
</profile>
</profiles>
...
/src/main/resources/database.properties
...
jdbc.driver=${jdbc.driver}
jdbc.url=${jdbc.url}
jdbc.user=${jdbc.user}
jdbc.password=${jdbc.password}
...
指定一個Maven簡介/src/main/resources/spring/applicationContext.xml
<beans ... xmlns:p="http://www.springframework.org/schema/p" ...>
...
<bean
id="dataSource"
...
p:driverClassName="${jdbc.driver}"
p:url="${jdbc.url}"
p:username="${jdbc.user}"
p:password="${jdbc.password}"
... />
...
</beans>
/src目錄/ 測試 /java/com/company/project/service/MyItemServiceImplTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/applicationContext.xml" })
public class MyItemServiceImplTest {
@Resource
private MyItemService myItemService;
@Test
public void testSave() {
MyItem myItem = new MyItem();
myItemService.save(myItem);
...
}
}
問題
當運行測試,它拋出一個異常:
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'dataSource' defined in class path resource [spring/applicationContext.xml]: Could not resolve placeholder 'database.password'
...
我想這是因爲我需要運行測試,同時指定dev
配置文件li我在啓動webapp時使用(使用-P dev
)。但我無法讓它工作。它甚至有可能嗎?
PS
將過濾applicationContext.xml文件(即,一種在/target/classes/spring/applicationContext.xml)等同於一個在/ SRC/*,但過濾database.properties文件(即/target/classes/database.properties)看起來像
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://${database.host}/${database.name}
jdbc.user=${database.user}
jdbc.password=${database.password}
這意味着從pom.xml文件到的.properties之一,性能得到了很好的過濾,但pom.xml的本身,取決於所選配置文件的屬性將不會被過濾。可能是因爲我想在啓動測試時指定我需要的配置文件的任何位置。但正如我以前說過的,-P dev
似乎並沒有工作和JUnit ......在process-resources
階段進行的
「applicationContext.xml」文件在過濾後看起來像什麼? – maba
@maba我應該如何處理以獲得過濾的? – sp00m
如果你按照我的最後[回答](http://stackoverflow.com/questions/12579712/initialize-a-constant-for-junit-from-a-properties-file-which-get-itself-initial/12580154# 12580154)我向你展示瞭如何過濾資源。如果你用'mvn compile'構建,你將會通過['process-resources'](http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference)階段,你的'target/classes /'文件夾,你將有過濾資源。 – maba