我有一個自定義ApplicationContext類,我嘗試以編程方式加載PropertyPlaceholderConfigurer,然後在我的XML配置文件中使用佔位符。PropertyPlaceholderConfigurer無法以編程方式加載
我已經試過三種不同的方法,到目前爲止,每一次我得到這樣一個錯誤:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named '${domain}.testId' is defined
我做錯了嗎?
Context類
public class MyApplicationContext extends GenericApplicationContext {
public MyApplicationContext (String... locations) throws IOException {
// method one
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this);
scanner.scan("com.my.package");
// method two
new MyPropertyPlaceholderConfigurer().postProcessBeanFactory(getBeanFactory());
// method three
getBeanFactory().registerSingleton("propertyPlaceholderConfigurer", new MyPropertyPlaceholderConfigurer());
// load XML config files
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(this);
for (String location : locations) {
xmlReader.loadBeanDefinitions(location);
}
}
}
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="test.testId" class="java.lang.String">
<constructor-arg value="this is the test value" />
</bean>
<bean id="prod.testId" class="java.lang.String">
<constructor-arg value="this is the prod value" />
</bean>
<alias name="${domain}.testId" alias="testId" />
</beans>
使用
MyApplicationContext context = new MyApplicationContext(
new String[] { "test.xml" });
Assert.assertEquals("this is the test value", context.getBean("testId"));
爲什麼你需要一個自定義上下文來包含一個'PropertyPlaceholderConfigurer'甚至你自己定製的上下文? – beny23 2013-02-25 20:21:10
我的上下文類也做包掃描和日誌初始化。我只是沒有在我的示例代碼中包含額外的東西。我對Spring很新,但它似乎是包含所有這些東西的合理位置。我錯了嗎? – MikeWyatt 2013-02-25 20:42:32