![](/img/trans.png)
[英]Spring @Configuration file with PropertyPlaceholderConfigurer bean doesn't resolve @Value annotation
[英]Spring PropertyPlaceholderConfigurer doesn't inject values
我已经花了几个小时进行谷歌搜索,但仍然无能为力。
使用调试器,我可以发现数据源中的用户和密码未替换为属性文件中的值,而是分别按${jdbc.user}
和${jdbc.password}
进行解析。
我究竟做错了什么?
这是jdbc.properties文件(位于src / main / resources):
jdbc.username=user
jdbc.password=password
这是spring配置xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>jdbc.properties</value>
</property>
</bean>
...
这是来自pom.xml的依赖项:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
问题是您启动应用程序的方式。
XmlBeanFactory parent = new XmlBeanFactory(new ClassPathResource("Parent.xml",SomeClass.class));
final XmlBeanFactory springBeanFactory = new XmlBeanFactory(new ClassPathResource(getClass().getSimpleName() + ".xml", getClass()), parent);
不要使用BeanFactory
使用ApplicationContext
。
String context = getClass().getSimpleName() + ".xml";
ApplicationContext parent = new ClassPathXmlApplicationContext("Parent.xml");
ApplicationContext child = new ClassPathXmlApplicationContext(new String[] {context}, parent);
BeanFactory
只是bean的工厂,仅此而已。 ApplicationContext
是类固醇上的BeanFactory
。 它具有完整的生命周期,并具有在该生命周期中调用的特殊类型的bean。
检查参考指南的这一部分 。
另一个技巧是,使用名称空间而不是bean声明来配置占位符支持,并且明智的做法是在其希望加载的位置/方式上添加前缀。
<context:property-placeholder location="classpath:/jdbc.properties" />
关于占位符支持的最终决定。 此类是BeanFactoryPostProcessor
,它将处理Bean定义并替换其中的占位符。 但是,它仅对同一应用程序上下文中的bean执行此操作! 如果您在父级中定义了该bean,并期望它在子级上下文中替换占位符,那么那将不会发生。
您需要告诉Spring在类路径中搜索属性文件,否则它将无法找到它。 将属性文件的位置从jdbc.properties
更改为classpath:/jdbc.properties
。
尝试使用此解析器:
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.