In the official document 2.5 version of the autowired is based on the type of injection, online search is also said that autowired by default is injected by type, and resource is the default by name injection, but later found not so, autowired injection type is related to the name of the variable, not to say, also It's the same as the first code description.
I have a bean interface, and then there is a bean1,bean2,bean3,3 bean, the code is as follows
public interface Bean {} @Componentpublic class Bean1 {@Autowiredprivate bean bean;public bean Getbean () {return bean;}} @Componentpublic class Bean2 implements bean{@Overridepublic String toString () {return ' Bean2 ....}} @Componentpublic class Bean3 implements bean{@Overridepublic String toString () {return ' Bean3 ....}}
where Bean2 and Bean3 implement the Bean interface, Bean1 has a bean type bean (named Bean), then the test code is as follows
public static void Main (string[] args) {ApplicationContext ctx = new Classpathxmlapplicationcontext (" Applicationcontext.xml "); Bean1 B1 = (Bean1) ctx.getbean ("Bean1"); System.out.println (B1.getbean ());}
As previously understood, this would be an error, because when spring injects the attribute bean into Bean1, it will find that there are two beans (bean2 and bean3) that implement the Bean interface in the container, and the result is the same as expected
No unique bean of type [bean. Bean] is defined:expected single matching bean but found 2: [Bean2, Bean3]
This is a report error, said to have found two matching beans
But this time if the attribute name in Bean1 changed to Bean2, and then run the test code, you will find out
Bean2 ....
If you change to BEAN3, it will be played
Bean3 ....
At that time, it felt a little strange, feeling should be wrong, because there are two bean types of beans, but the result seems to be not so, and then I changed the name to Bean4, this time again error, the mistake and the above, is found two beans
According to the above test, we get the conclusion:
1.Autowired is the bean that first names the same ID in the container based on the name of the variable.
2. If found, inject
3. If not found, search by type
4. If the type is found and there is only one bean of that type, then injection, find multiple beans of the same type and then error
Spring's @autowired need to be aware of the place