简体   繁体   English

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

[英]Spring: Programmatically use PropertyPlaceHolderConfigurer on none Singelton Beans

I'm aware that the following implementation of a PropertyPlaceHolderConfigurer is possible: 我知道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());
  }}

With this in the config file: 在配置文件中有这个:

<?xml version="1.0" encoding="UTF-8"?>

http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd "> 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>

However, this looks to me that the changes made to the testBean will be shown on all the test beans. 但是,这使我看到对testBean所做的更改将显示在所有测试bean上。

How do I use the propertyPlaceHolderCongfigurer in such a way that I can apply it to individual instances of the bean, and have access to each of these instances? 如何以这样的方式使用propertyPlaceHolderCongfigurer,我可以将它应用于bean的各个实例,并且可以访问这些实例中的每一个?

I hope the question makes sense. 我希望这个问题有道理。 Any help would be much appreciated. 任何帮助将非常感激。

By default Spring beans are singletons, that is subsequent calls to context.getBean("testBean") would return the same instance. 默认情况下,Spring bean是单例,即后续对context.getBean("testBean")调用将返回相同的实例。 If you want them to return different instances, you should set a scope = "prototype" on the bean definition: 如果希望它们返回不同的实例,则应在bean定义上设置scope = "prototype"

<bean id="testBean" class="com.spring.ioc.TestClass" scope = "prototype"> 
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM