java - Spring:以编程方式在非单例 Bean 上使用 PropertyPlaceHolderConfigurer

标签 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());
  }}

在配置文件中使用:

<?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/

相关文章:

java - List<Integer> 作为 JRBeanCollectionDataSource 到子报表中,如何获取报表上显示的整数值?

带有 p6spy 侦探跟踪解释的 spring boot

C#:如何为部分类中的属性设置默认值?

java - jUnit 中 void 方法和线程的单元测试

java - 禁用 Java 列表中的可变性

java - 无法合并Dex Android

java - 如何在不使用 spring AOP 的情况下创建代理

java - 为什么我从 Log4J 1.2.17 收到警告?

objective-c - 在 Objective C 中为弱属性创建自定义 setter 的正确方法是什么?

sql-server - Powershell将对象插入SQL Server数据库更优雅的解决方案