Issue
I need something like:
@Named({"bean1", "bean2"})
@Service({"bean1", "bean2"})
Can someone help me?
Solution
Not directly, the way you have it. But it is possible by redefining an existing @Service
(or @Component
) as a @Bean
with either a name or list of names, it is possible.
@Service("Service-A")
public class SampleService {
public String doSomething() { return "Foo"; }
}
@Configuration
public class SampleConfig {
@Bean(name = {"Service-B", "Service-C"})
public SampleService createMirroredService(@Autowired SampleService service) {
return service;
}
}
And now you have three instances of SampleService
: Service-A
(your @Service
), Service-B
, and Service-C
. This works because you define one and just have the @Bean
annotated method pass through the implementation, which has the effect of creating aliases. Make sure the configuration class is picked up in the scan and it should work fine.
Note: Although this works, and there are probably other solutions as well, I can't think of a case where I would need this. Perhaps if I'm integrating with a library that already exists that I can't change. But there doesn't strike me as a serious need for this, or else they would have made value
on @Component
an array.
Answered By - Todd
Answer Checked By - Katrina (JavaFixing Volunteer)