猿问

从枚举创建 singelton bean

我有一个如下所示的枚举


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名称连接。


慕雪6442864
浏览 108回答 2
2回答

蝴蝶不菲

编写自定义BeanFactoryPostProcessor来玩转 bean 定义。@Beanpublic BeanFactoryPostProcessor getBeanFactoryPostProcessor() {  return beanFactory -> {    for (int i = 0; i < MyBeanType.values().length; i++) {      beanFactory.registerSingleton(MyBeanType.class.getSimpleName() + i,         new MyBean(MyBeanType.values()[i]));    }  };}

慕妹3146593

您可以简单地以编程方式注册 bean。应该这样做。@Configurationpublic class MyBeanConfig() implements ApplicationContextAware {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void setApplicationContext(final ApplicationContext ctx) {&nbsp; &nbsp; &nbsp; &nbsp; final ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) ctx).getBeanFactory();&nbsp; &nbsp; &nbsp; &nbsp; for(final MyBeanType beanType: MyBeanType.values()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; beanFactory.registerSingleton(MyBean.class.getCanonicalName() + "_" + beanType, new MyBean(beanType));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答