1. Business scenarios
There are static methods in spring framework applications that need to rely on classes managed by containers, like this:
This will definitely report java.lang.NullPointerException: null exception.
2. Principle analysis
Static variables and class variables are not properties of objects, but properties of a class, so static methods belong to classes, ordinary methods belong to entity objects (i.e., new objects), and spring injection instantiates objects in containers, so static methods cannot be used.
The use of static variables and class variables expands the scope of use of static methods. Static methods are not recommended in spring, and the main purpose of dependency injection is to allow containers to generate instances of an object and then use them throughout their lifetime, while also making testing easier.
Once you use the static method, you no longer need to generate instances of this class, which makes testing more difficult, and you can't rely on injection to generate multiple instances with different dependencies for a given class, which is implicitly shared and is a global state, which is also not recommended by spring.
3. Solution
1. Add @Autowire to the construction method
2. Annotate with @PostConstruct
|