简体   繁体   中英

Create singelton beans from enum

I have an enum that looks like the following

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

I would like to create a Bean for each of these enum values.

public Class MyBean {
  private MyBeanType type;

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

I know I could list each of these in my config like so:

@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);  

}

But is there a way to do this more dynamically? I'm typically wiring all of these in as a List , but there are some instances where I'd like to wire myBeanType2 by name as well.

You could simply register the beans programmatically. Something like this should do it.

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

Write a custom BeanFactoryPostProcessor to play around with bean definitions.

@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]));
    }
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM