First application.yml configuration profile is as follows:
Maven project pom.xml add packages:
Create a new mapped object with the following code:
String type must need a setter to receive property values; maps, collections, and arrays are not required
Use @Autowired annotations to automatically inject, as shown in the following image:
esConfig always outputs null, searched for a solution for a long time, but failed, there will be a solution below.
Let's create a new controller, the code is as follows:
The injection is successful, and the values of the yml configuration file are obtained normally, as follows:
The reasons why EsClient cannot be injected successfully are as follows:
Call a function of this class in the constructor, and the variable of the @Autowired of this class is used in this function.
So I thought it might go wrong. Because @Autowired must wait for the class to be constructed before it can be set from external references. Therefore, the injection time of @Autowired must be later than the execution time of the constructor. Solution:
Spring Team recommends “Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies”.
Translation:
Spring suggests "Always establish dependency injection with constructors in your bean. always use assertions to force dependencies".
Original writing:
Modified writing:
PS: The initialization order of Java variables is: static variables or static statement blocks – > instance variables or initialization statement blocks – >construction method – >@Autowired
So why add the final type to the member variable?
There is an explanation on the Internet as follows: The scope of the default bean in the spring configuration is singleton, which is always there after startup. Declare the bean's object to be dynamically created by setting the scope property to prototype. However, if your service itself is a singleton, the injection is only executed once.
@Autowired itself is a singleton mode, it will only be executed once when the program starts, and it will not initialize a second time even if it does not define a final, so this final is meaningless.
It may be to prevent the constructor from being executed again while the program is running;
Or maybe it's easier to understand, plus final will only initialize once when the program starts.
|