How spring knows which polymorphic type to use.
As long as there is only one implementation of the interface, and this implementation is annotated with @Component with spring scanning enabled, the spring infrastructure can find a pair (interface, implementation). If component verification is not enabled, you need to explicitly define a bean in the application config-config.xml configuration file (or equivalent spring).
Do I need @Qualifier or @Resource?
After you have several implementations, you need to qualify each of them and during automatic posting, you will need to use the @Qualifier annotation to enter the correct implementation along with the @Autowired annotation. If you use @Resource (J2EE semantics), then you must specify the bean name using the name attribute of this annotation.
Why do we use an autwire interface and not an implemented class?
Firstly, it is always good practice to code interfaces in general. Secondly, in the case of spring, you can implement any implementation at run time. A typical use case is the introduction of a mock implementation at the testing stage.
interface IA { public void someFunction(); } class B implements IA { public void someFunction() {
The bean configuration should look like this:
<bean id="b" class="B" /> <bean id="c" class="C" /> <bean id="runner" class="MyRunner" />
Alternatively, if you enable component checking in the package where they are present, you should qualify each class with @Component as follows:
interface IA { public void someFunction(); } @Component(value="b") class B implements IA { public void someFunction() {
Then, an instance of type B will be introduced in MyRunner .
Vikdor Oct. 15 2018-12-15T00: 00Z
source share