Explain spring @ Autowired injection tips in detail
When discussing spring automatic injection with my colleagues today, I found that such a piece of code is particularly confused. Of course, the general principle is understandable, but it has never been used like this before. Thinking that it may be used in the future, or that it will not take time to solve the same confusion when looking at the code written by others in the future, Xiaobian still feels it necessary to study and record it.
1、 The same type is injected into the same instance multiple times
First, let's look at what this code is?
XiaoMing. java
We all know that @ Autowired can inject automatically according to the type, and the default injected bean is singleton, so we may ask, will the above two injections not be repeated? The answer is yes. And each injected instance is the same instance. Let's briefly verify:
After calling the above interface, the following contents will be output. You can see that they are the same instance.
2、 Injection interface type instance
If the type we want to inject is declared as an interface type and the interface has more than one implementation class, can the following code still run normally? We assume that student is the interface and Wanger and Xiaoming are two implementation classes.
The answer is that the above code can not run normally, and spring also starts to report an error. The reason is that spring wants to inject a single instance into the student, but unexpectedly finds two during the injection process, so it reports an error. The specific error information is as follows:
What should I do? In general, we will think of assigning an ID value to each implementation class. As a result, we have the following code:
After completing the above configuration, spring will go to the bean factory by default to find the corresponding bean for injection according to the field name. Note that the name can not be taken arbitrarily, but should be consistent with the injected property name.
3、 Summary
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.