我有一个如下所示的枚举
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
。
答案 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]));
}
};
}