Paleozoic opened SPR-17441 and commented
When inject two beans,such as the following code:
@Bean("bean1")
public Bean buildBean1(){
Bean bean = new Bean();
return bean ;
}
@Bean("bean2")
public Bean buildBean2(){
Bean bean = new Bean();
return bean ;
}
can I just write the code? such as:
@Beans
public Map<String,Bean> buildBeans(){
Map<String,Bean> beans = new HashMap<>();
beans.put("bean1",new Bean());
beans.put("bean2",new Bean());
return beans ;
}
sometimes we can not confirm how many beans to inject,we have to write complex BeanDefinition
and then registerBeanDefinition
.
if we have @Beans
,everything is easy~
Affects: 5.1.1
Comment From: spring-projects-issues
Zhang Jie commented
If you don't confirm how many beans to inject, using @Component
and @ComponentScan
will help, it's not necessary to define every bean using @Bean
.
Comment From: spring-projects-issues
Paleozoic commented
can @Component
and @ComponentScan
inject beans dynamically?
we also need to write java code to define beans and then scan components.
I mean that we can only use the yml configuration to inject beans dynamically.
for example,the above code shows that @Beans
can inject beans dynamically ,we just need to handle the yml configuration in the buildBeans
method.
such as we inject the datasources dynamically…
Comment From: snicoll
There isn't such way to declare beans in a generic fashion but the framework offers several hooks points. You could import an ImportBeanDefinitionRegistrar
on a configuration class and you'll get a callback to register any bean you want. If those beans are singleton, you can also register them programmatically.