从枚举创建辛格尔顿豆

时间:2019-08-15 04:42:41

标签: java spring configuration autowired

我有一个如下所示的枚举

public enum MyBeanType {
  Type1,
  Type2
  ...
  Type100;
}

我想为每个这些枚举值创建一个Bean。

public Class MyBean {
  private MyBeanType type;

 public MyBean(MyBeanType type) { this.type = type; }
}

我知道我可以像这样在我的配置中列出每一个:

@Configuration
public class MyBeanConfig() {

  @Bean public MyBean myBeanType1() { return new MyBean(MyBeanType.Type1);
  @Bean public MyBean myBeanType2() { return new MyBean(MyBeanType.Type2);
  ... 
  @Bean public MyBean myBeanType100() { return new MyBean(MyBeanType.Type100);  

}

但是有办法更动态地做到这一点吗? 我通常将所有这些都连接为List,但在某些情况下,我也想按名称连接myBeanType2

2 个答案:

答案 0 :(得分:1)

您可以简单地以编程方式注册Bean。像这样的事情应该做。

@Configuration
public class MyBeanConfig() implements ApplicationContextAware {

    @Override
    public void setApplicationContext(final ApplicationContext ctx) {

        final ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) ctx).getBeanFactory();

        for(final MyBeanType beanType: MyBeanType.values()) {

            beanFactory.registerSingleton(MyBean.class.getCanonicalName() + "_" + beanType, new MyBean(beanType));
        }
    }
}

答案 1 :(得分:1)

编写一个自定义BeanFactoryPostProcessor来使用bean定义。

@Bean
public BeanFactoryPostProcessor getBeanFactoryPostProcessor() {
  return beanFactory -> {
    for (int i = 0; i < MyBeanType.values().length; i++) {
      beanFactory.registerSingleton(MyBeanType.class.getSimpleName() + i, 
        new MyBean(MyBeanType.values()[i]));
    }
  };
}