gpt4 book ai didi

java - junit/spring 属性未加载应用程序上下文

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:11:25 25 4
gpt4 key购买 nike

在运行 junit 测试时,我无法获取应用程序上下文以从外部属性文件加载属性。

鉴于以下情况:

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/app-config.xml")
public class JdbcWatsonDaoTests {

@Autowired
JdbMyDao jdbcMyDao;

@Before
public void setUp() throws Exception {
}

@Test
public void testMethod() {
doSomeStuff();
}
}

应用配置文件

<util:properties id="aProperties" location="classpath:spring/a.properties" />
<util:properties id="bProperties" location="classpath:spring/b.properties" />

<bean id="oracleDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="${oracle.url}"/>
<property name="username" value="${oracle.username}"/>
<property name="password" value="${oracle.password}"/>
</bean>

并且 a.properties 和 b.properties 文件与 app-config.xml 位于同一位置...

我发现在运行测试时,属性占位符(文字“${property}”)是发送到 oracle 服务器的内容,而不是属性文件中的值。

我也尝试过使用 PropertyPlaceholderConfigurer 而不是使用 bean 配置,但它仍然找不到/包含属性。

我正在使用 eclipse helios、spring 3.0.5、最新版本 m2eclipse 和 4.4 junit。我不得不为不同的 maven/junit bug 降级 junit。

在 tomcat 中发布时,会读取并正确使用属性。我只在运行 junit 测试时看到问题。

最佳答案

根据您的异常(exception)情况:

org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (ORA-01017: invalid username/password; logon denied

您的问题不是未找到属性,如果未找到属性,异常将类似于 org.springframework.beans.factory.BeanDefinitionStoreException: ... Could not resolve placeholder 'oracle.username '

这是因为您需要配置 PropertyPlaceholderConfigurer 而不是PropertiesFactoryBean(这是 util:properties 所做的 http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#xsd-config-body-schemas-util-properties )

<bean id="propertyPlaceHolderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:spring/a.properties</value>
<value>classpath:spring/a.properties</value>
</list>
</property>
</bean>

关于java - junit/spring 属性未加载应用程序上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4215530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com