我知道 PropertyPlaceHolderConfigurer 的以下实现是可能的:
public class SpringStart {
public static void main(String[] args) throws Exception {
PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
Properties properties = new Properties();
properties.setProperty("first.prop", "first value");
properties.setProperty("second.prop", "second value");
configurer.setProperties(properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
context.addBeanFactoryPostProcessor(configurer);
context.setConfigLocation("spring-config.xml");
context.refresh();
TestClass testClass = (TestClass)context.getBean("testBean");
System.out.println(testClass.getFirst());
System.out.println(testClass.getSecond());
}}
在配置文件中使用:
<?xml version="1.0" encoding="UTF-8"?>
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd ">
<bean id="testBean" class="com.spring.ioc.TestClass">
<property name="first" value="${first.prop}"/>
<property name="second" value="${second.prop}"/>
</bean>
但是,在我看来,对 testBean 所做的更改将显示在所有测试 bean 上。
我如何使用 propertyPlaceHolderCongfigurer 才能将其应用于 bean 的各个实例,并有权访问这些实例中的每一个?
我希望这个问题是有道理的。任何帮助将不胜感激。
最佳答案
默认情况下,Spring bean 是单例,即后续调用 context.getBean("testBean")
将返回相同的实例。如果你想让它们返回不同的实例,你应该在 bean 定义上设置一个 scope = "prototype"
:
<bean id="testBean" class="com.spring.ioc.TestClass" scope = "prototype">
...
关于java - Spring:以编程方式在非单例 Bean 上使用 PropertyPlaceHolderConfigurer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2356995/