Java 定义';*。属性';Spring中的文件位置

Java 定义';*。属性';Spring中的文件位置,java,spring,properties,Java,Spring,Properties,我有几个bean的Spring上下文,比如: <bean id="anyBean" class="com.my.app.AnyBean" p:test_user="${any1}" p:test_pass="${any2}"> </bean> 但当我尝试启动它时: 线程“main”中出现异常 org.springframework.beans.factory.BeanDefinitionStoreException: 类路径中定义了名为“AnyBean”的无

我有几个bean的Spring上下文,比如:

<bean id="anyBean" class="com.my.app.AnyBean"
   p:test_user="${any1}"
   p:test_pass="${any2}">
</bean>
但当我尝试启动它时:

线程“main”中出现异常 org.springframework.beans.factory.BeanDefinitionStoreException: 类路径中定义了名为“AnyBean”的无效bean定义 资源[my_xml\u config.xml]:无法解析中的占位符“any1” 字符串值“${any1}”


你能告诉我有什么办法可以解决这个问题吗?

当你试图得到一个bean时

PropertyPlaceholderConfigurer ppc = context.getBean("propertyPlaceholderConfigurer", PropertyPlaceholderConfigurer.class);
Spring已尝试刷新您的上下文,但由于属性不存在而失败。您需要通过以下方式防止Spring执行此操作:

由于未刷新
ApplicationContext
,因此
PropertyPlaceHolderConfiguration
bean不存在

为此,您需要使用而不是
PropertyPlaceHolderConfigure
(感谢M.Deinum)。您可以使用与
PropertyPlaceholderConfigurer
bean相同的方式在XML中声明它,或者使用

<context:property-placeholder />

PropertyPlaceholderConfigurer
不查阅
PropertySource
s,而
propertysourcesplaceplaceplaceconfigurer
查阅。不要配置bean,而是使用
标记,该标记默认(在最近的spring版本中)为
PropertySourcesPlaceholderConfigurer
@M.Deinum,OP希望以编程方式设置属性位置。我想
不是一个选项。为什么不呢,您仍然可以使用它的location属性。将文件名设置为系统属性,spring将使用它。PropertyPlaceHolderCongigurer是否应保留在XML spring cofig中?
PropertyPlaceholderConfigurer ppc = context.getBean("propertyPlaceholderConfigurer", PropertyPlaceholderConfigurer.class);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"my_xml_config.xml"}, false);
<context:property-placeholder />
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"your_config.xml"}, false);
// all sorts of constructors, many options for finding the resource
ResourcePropertySource properties = new ResourcePropertySource("path/to/my.properties");
context.getEnvironment().getPropertySources().addLast(properties);
context.refresh();