开发者

Adding more values to a property of an existing bean

In my config, I have a bean paths. Now depending on which config file is read, I need to add paths to this property.

Or to put it another way: How can I set a property multiple times on an existing bean?

The standard syntax <bean id="..." class="...."> always creates a new bean.

I tried to create an "appender" bean, make that non-lazy but for some reason, the paths bean isn't injected:

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 );
     }
}

and in the Spring config:

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


You can implement it as a 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;
     }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜