![](/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.