![](/img/trans.png)
[英]Spring - “context:property-placeholder” - property priority
[英]Spring from scratch - Bug on context:property-placeholder
我正在使用Spring在非常非常简单的应用程序上进行测试。
我的应用程序只有一个bean ,我正在向该类注入一个简单的String并输出该值。 到目前为止,一切正常 。
我想从配置文件中获取此字符串,所以我在/ src / main / resource中创建文件
我做了什么:
1)在我的application-context.xml文件中添加:
<context:property-placeholder location="classpath:myConfigFile.properties" />
2)在我的application-context.xml中,我从简单的String更改为使用$ {name_test}:
<bean id="hello" class="com.dummy.SayHello">
<property name="name" value="${name_test}" />
</bean>
3)我仔细检查myConfigFile.properties并包含“ name_test = JackTheRipper”
4)但是我的输出没有“转换”配置文件中的值,当我运行我的应用程序时,我得到了以下输出:
Hello ${name_test}
我被困在这里,任何线索,提示???
仅供参考
mvn clean编译exec:java
根本原因是我如何在java类上获取application-context.xml 。
我在做:
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("application-context.xml"));
然后在这篇文章之后,我将其更改为:
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
我在这里可以想象的唯一问题是,您使用BeanFactory
而不是ApplicationContext
。 与ApplicationContext
相比, BeanFactory
缺少一些高级功能,包括<context:property-placeholder>
必需的后处理器自动注册。
只是出于好奇,而不是使用<context:property-placeholder>
,您可以尝试一下吗?
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:myConfigFile.properties</value>
</property>
</bean>
如果这样不起作用,请尝试在classpath
后classpath
*
:-
<context:property-placeholder location="classpath*:myConfigFile.properties" />
您的配置很好。 我的猜测是,您的属性文件无法在类路径上找到。 关于配置器,是否有任何Spring日志记录? 尝试运行:
mvn clean install exec:java
这将创建一个工件(jar),该工件将捆绑您的src/main/resources
内容,而编译显然只是将源文件编译为类文件。
我也可以尝试一个测试用例。 将pom测试添加到pom:
聚甲醛
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>[YOUR SPRING VERSION]</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8</version>
</dependency>
测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:application-context.xml")
public class TestSayHello
{
@Autowired
@Qualifier("hello")
private SayHello hello;
@Test
public void testSayHello()
{
Assert.assertNotNull(hello);
Assert.assertEquals("JackTheRipper", hello.getName());
}
}
no id或name消息只是警告,因为您的bean不包含任何一个。 如果找不到您的配置文件,则也应该显示一条消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.