views:

283

answers:

1

Is there a way in Spring to create a collection, or array, of beans, based on a comma-separated list of classes. For example:

package mypackage;
public class Bla {
 private Set<MyBean> beans;
 public void setBeans(Set<MyBean> beans) {
  this.beans = beans;
 }
}

With the application context:

<bean id="bla" class="mypackage.Bla">
 <property name="beans">
  <set>
   <bean class="mypackage.Bean1, mypackage.Bean2" />
  </set>
 </property>
</bean>

Preferably the beans are all initialized and wired from the context, leaving the code as simplistic as possible, is this possible?

A: 

Use a combination of ApplicationContextAware and ApplicationListener:

public class BeanInitializer implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {

    private ApplicationContext  context;
    private List<Class<?>>      beanClasses;

    public void onApplicationEvent(final ContextRefreshedEvent event) {
        final AutowireCapableBeanFactory beanFactory = this.context.getAutowireCapableBeanFactory();
        for (final Class<?> beanClass : this.beanClasses) {
            beanFactory.autowire(beanClass, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
        }
    }

    public void setApplicationContext(final ApplicationContext context) throws BeansException {
        this.context = context;
    }

    public void setBeanClasses(final List<Class<?>> beanClasses) {
        this.beanClasses = beanClasses;
    }

}

in your spring config, do this:

<bean class="com.yourcompany.BeanInitializer">
<property name="beanClasses">
    <list>
        <value>com.yourcompany.Type1</value>
        <value>com.yourcompany.Type2</value>
        <value>com.yourcompany.Type3</value>
    </list>
</property>
</bean>

Edited: Actually, if you want comma separated, it will probably be more like this:

<bean class="com.yourcompany.BeanInitializer">
<property name="beanClasses" 
        value="com.yourcompany.Type1,com.yourcompany.Type2,com.yourcompany.Type3" />
</bean>

I don't know if there is a built-in property editor that converts a comma delimited string to a list of classes but if not you can either create one yourself or change your setter method to accept a string and parse the string yourself

seanizer
There is an appropiate property editor for String to Class[], thanks.
Jeroen
@Jeroen: Does that answer your question, then?
skaffman