Aaron Digulla
Aaron Digulla

Reputation: 328536

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>

Upvotes: 1

Views: 3035

Answers (1)

axtavt
axtavt

Reputation: 242686

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

Upvotes: 2

Related Questions