Reputation: 895
what rules govern the mapping of beans (dependencies) to injection candidates (eligible for injection of a dependency) ?
Say in a configuration file there is a builder function
@Autowired
MyFacilityInstance myFacility = MyFacilityConfigurer.builder()
.setA(ITypeA someIndentifierA),
.setB(ITypeB someIdentifierB));
and I want to write beans to provide Instances for these two parameters by writing two beans.
What is the identifier of the bean function? Is the identifier of the bean function the name of the Interface to be injected? And how do I type the bean-function (a.k.a dependency)? With the Interface to be instantiated or with the symbol for one of its' implementations?
@Bean
SomeImplementationA iTypeA() {
return new SomeImplementationA();
}
@Bean
SomeImplementationA iTypeA() {
return new SomeImplementationA();
}
In this example I used Interfaces to be injected. But does this also work with normal classes that are injected with other subclasses?
I'm sure this is not all there is to the complexity of this mapping.
Can you please answer my question insofar as is needed to correctly write Beans for other parts of a configuration file?
And where can I read more on these rules? Do you have a source for me?
Upvotes: 1
Views: 47
Reputation: 409
What is the identifier of the bean function? Is the identifier of the bean function the name of the Interface to be injected? And how do I type the bean-function (a.k.a dependency)? With the Interface to be instantiated or with the symbol for one of its' implementations?
An identifier could be that the bean implements a given interface of your type to inject, as in your example. This works with class as well, but it's less common. By type injection limits the total implementations that can be used in the IoC the exactly one bean per class-type, so can be uniquely identified in the given scope. On the other hand, you can extend the identification of a bean using with a name and reference to this name on the injection side (named bean).
In this example I used Interfaces to be injected. But does this also work with normal classes that are injected with other subclasses?
Yes, there is no obligation to use interfaces, but in practice you benefit a lot of using interfaces (i.e. decoupling from the implementation), so that the dependency does not rely on implementation specialities that are not specified in the interface, making it more feasible to inject a different bean implementation, such as often done in testing.
If you are using Spring IoC, which is quite popular, these documentations might help you. They are also mostly valid for other IoC containers.
For naming beans:
Upvotes: 1