/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