向现有bean的属性添加更多值

时间:2011-04-04 09:24:56

标签: spring configuration javabeans

在我的配置中,我有一个bean paths。现在,根据读取的配置文件,我需要添加路径到此属性。

或者换句话说:如何在现有 bean上多次设置属性?

标准语法<bean id="..." class="....">总是会创建一个新的bean。

我尝试创建一个“appender”bean,使其非懒惰,但由于某种原因,paths bean没有被注入:

public class Appender {
     private Paths paths;

     // Never called :-(
     @Required @Autowired
     public void setPaths( Paths paths ) { this.paths = paths; }

     public void setAdditionalPaths( List<String> paths ) {
          this.paths.add( paths );
     }
}

并在Spring配置中:

<bean id="addMorePaths" class="Appender" depends-on="paths" lazy-init="false">
     <property name="additionalPaths">
         <list>...</list>
     </property>
</bean>

1 个答案:

答案 0 :(得分:2)

您可以将其实施为BeanPostProcessor

public class Appender implements BeanPostProcessor {
     private List<String> paths;

     public void setAdditionalPaths( List<String> paths ) {
          this.paths = paths;
     }

     public Object postProcessAfterInitialization(String name, Object bean) {
         if ("paths".equals(name)) {
             ((Paths) bean).add(paths);
         }
         return bean;
     }

     public Object postProcessBeforeInitialization(String name, Object bean) {
         return bean;
     }
}