【问题标题】:Spring: Programmatically use PropertyPlaceHolderConfigurer on none Singelton BeansSpring:以编程方式在非单例 Bean 上使用 PropertyPlaceHolderConfigurer
【发布时间】:2011-01-22 08:31:22
【问题描述】:

我知道 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 的各个实例,并可以访问每个实例?

我希望这个问题是有意义的。任何帮助将不胜感激。

【问题讨论】:

    标签: java spring properties


    【解决方案1】:

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

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

    【讨论】:

    • 在庆祝之前,我只想确认点击 context.refresh 按钮不会更新此 bean 的过去实例?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    相关资源
    最近更新 更多