Spring:在没有Singelton Beans的情况下以编程方式使用PropertyPlaceHolderConfigurer

Bab*_*e86 6 java spring properties

我知道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());
  }}
Run Code Online (Sandbox Code Playgroud)

在配置文件中有这个:

<?xml version="1.0" encoding="UTF-8"?>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

但是,这使我看到对testBean所做的更改将显示在所有测试bean上.

如何以这样的方式使用propertyPlaceHolderCongfigurer,我可以将它应用于bean的各个实例,并且可以访问这些实例中的每一个?

我希望这个问题有道理.任何帮助将非常感激.

axt*_*avt 2

默认情况下,Spring bean 是单例的,即后续调用context.getBean("testBean")将返回相同的实例。scope = "prototype"如果您希望它们返回不同的实例,您应该在 bean 定义上设置:

<bean id="testBean" class="com.spring.ioc.TestClass" scope = "prototype"> 
...
Run Code Online (Sandbox Code Playgroud)