我的 pom.xml 中有这个:
<build>
<finalName>${project.artifactId}</finalName>
<filters>
<filter>${project.basedir}/src/main/resources/filters/${env}.properties</filter>
</filters>
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<testResources>
<testResource>
<directory>${project.basedir}/src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
</build>
...
<profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>qa</id>
<properties>
<env>qa</env>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
我在 src/main/resources/filters 中有这些文件:dev.properties、qa.properties 和 prod.properties。
但是我在 src/test/resource 中的 spring 配置 test-db-config.xml 没有获取属性文件中的值:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>${db.driver}</value>
</property>
<property name="url">
<value>${db.url}</value>
</property>
<property name="username">
<value>${db.usename}</value>
</property>
<property name="password">
<value>${db.password}</value>
</property>
</bean>
有人能指出我正确的方向吗?谢谢
这是我遇到的错误:
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.185 sec <<< FAILURE!
testCustomerExists(com.xxxx.hcs.persistence.repository.CustomerRepositoryTest) Time elapsed: 1.973 sec <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
...
在 dev.properties 我有:
db.driver=oracle.jdbc.OracleDriver
db.url=jdbc:oracle:thin:@hrsdev.xxxx.net:1548:yyyy
db.usedb.passwordrname=xxxx
db.password=yyyy
当我将这些值放入 test-db-config.xml 时,测试用例运行良好。所以我知道这是由变量替换引起的。
最佳答案
我的直觉是过滤器在过滤操作之前被解析,所以 ${env} 变量还没有被计算并且过滤器永远不会被解析。
您可以通过在 pom 中直接设置全名“dev.properties”来测试它,这应该会导致有效的过滤。
我建议使用经典方式,直接将您的属性值放入配置文件定义中(参见 http://www.manydesigns.com/en/portofino/portofino3/tutorials/using-maven-profiles-and-resource-filtering)。
这不会阻止使用属性文件进行配置,只需要一个包含变量的属性文件 (dbConfig.properties),并让它由 maven 过滤。
[编辑]
似乎最先进的方法是使用 propertyConfigurer
bean,参见 https://stackoverflow.com/a/11874827/2087640
关于java - Spring 测试配置忽略 Maven 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22996446/