在 Spring 中定义“*.properties”文件位置

Define '*.properties' file location in Spring

我有 Spring 包含多个 bean 的上下文,例如:

<bean id="anyBean" class="com.my.app.AnyBean"
   p:test_user="${any1}"
   p:test_pass="${any2}">
</bean>

为了解析这些占位符(${any1} 和 ${any2}),我使用:

<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="my.properties" />

它工作正常,但我需要从主要 class 的 'main' 方法定义 'my.properties' 的位置。像这样:

ApplicationContext context = new ClassPathXmlApplicationContext(my_xml_config.xml);
PropertyPlaceholderConfigurer ppc = context.getBean("propertyPlaceholderConfigurer", PropertyPlaceholderConfigurer.class);

Resource resource = context.getResource("path/to/my.properties");
ppc.setLocation(resource);

但是当我尝试启动它时:

Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'AnyBean' defined in class path resource [my_xml_config.xml]: Could not resolve placeholder 'any1' in string value "${any1}"

请问有什么办法可以解决这个问题吗?

当你尝试获取豆子时

PropertyPlaceholderConfigurer ppc = context.getBean("propertyPlaceholderConfigurer", PropertyPlaceholderConfigurer.class);

Spring 已经尝试刷新您的上下文但由于 属性 不存在而失败。您需要通过 specifying it in the constructor

来阻止 Spring 这样做
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"my_xml_config.xml"}, false);

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

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

<context:property-placeholder />

您需要利用 PropertySourcesPlaceholderConfigurer 有自己的位置这一事实,而且还使用在 ApplicationContextEnvironment 中注册的 PropertySource 个实例。

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();