Reputation: 7743
In the following Spring Java Config:
@Configuration
@EnableAutoConfiguration
@ComponentScan("my.package")
public class Config {
@Bean
public BasicBean basicBean1() {
return new BasicBean("1");
}
@Bean
public BasicBean basicBean2() {
return new BasicBean("2");
}
@Bean
public ComplexBean complexBeanByParameters(List<BasicBean> basicBeans) {
return new ComplexBean(basicBeans);
}
@Bean
public ComplexBean complexBeanByReferences() {
return new ComplexBean(Arrays.asList(basicBean1(), basicBean2()));
}
}
I can create two ComplexBean
s using either parameter injection, which is elegant, but has shortcomings if a have a few other beans of BasicBean
type and only want a few (the parameters can of course be of type BasicBean
and enumerate by name the beans I'm interested of, but it could turn out to be a very long list, at least for arguments sake). In case I wish to reference the beans directly I might use the complexBeanByReferences
style, which could be useful in case of ordering or some other consideration.
But say I want to use the complexBeanByReference
style to reference the bean complexBeanByParameters
, that is something along the line of:
@Bean
public ComplexBeanRegistry complexBeanRegistry() {
return new ComplexBeanRegistry(
Arrays.asList(
complexBeanByParameters(), // but this will not work!
complexBeanByReferences()
)
);
}
How would I reference complexBeanByParameters
, without having to specify a list of dependencies to complexBeanRegistry
? Which, the latter in all honesty should be completely oblivious of.
There is the option to just use
public ComplexBeanRegistry complexBeanRegistry(List<ComplexBeans> complexBeans) {...}
of course, but this might not be an option in certain cases, specifically when using the CacheConfigurer
from spring-context
. In this case the Java Config is intended to
CacheConfigurer
, override the default instances of the CacheManager
and KeyGenerator
beans.The requirement to implement CacheConfigurer
means I can't change the signature to use parameter injection.
So the question is, is there a way to reference complexBeanByParameters
using the "direct" reference style?
Upvotes: 3
Views: 256
Reputation: 1479
Maybe you could reference it with separation by Qualifier:
@Bean
@Qualifier("complexBeanParam")
public ComplexBean complexBeanByParameters(List<BasicBean> basicBeans) {
return new ComplexBean(basicBeans);
}
@Bean
@Qualifier("complexBeanRef")
public ComplexBean complexBeanByReferences() {
return new ComplexBean(Arrays.asList(basicBean1(), basicBean2()));
}
and for example autowire:
@Autowired
@Qualifier("complexBeanParam")
private ComplexBean beanParam;
Upvotes: 1