基于逗号分隔的类列表创建spring bean

时间:2010-05-18 06:42:40

标签: spring javabeans csv

Spring是否有办法根据逗号分隔的类列表创建bean的集合或数组。例如:

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

使用应用程序上下文:

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

最好将bean全部初始化并从上下文连线,尽可能简化代码,这可能吗?

1 个答案:

答案 0 :(得分:1)

使用ApplicationContextAware和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;
    }

}
在你的spring配置中

执行此操作:

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

编辑:实际上,如果你想要逗号分隔,它可能更像是这样:

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

我不知道是否有内置属性编辑器将逗号分隔的字符串转换为类列表但如果没有,您可以自己创建一个或更改setter方法以接受字符串并解析字符串自己