A static method belongs to the class, and the normal method belongs to the entity object (that is, the new object), and spring injection is the instantiation of the object in the container, so the static method cannot be used
In Springframework, we cannot @autowired a static variable to make it a spring bean, such as the following:
[Java]
- @Autowired
- Private static YourClass YourClass;
Can try, yourclass in this state can not be dependent injection, will throw run-time exception java.lang.NullPointerException, why? The static variable/class variable is not an object's property, but a property of a class. Spring is based on dependency injection at the object level.
Static variables/class variables are used to extend the use of static methods. Static methods are not recommended in spring. The primary purpose of dependency injection is to allow the container to produce an instance of an object, and then use them throughout the life cycle, while also making testing easier to work with.
Once you use static methods, it is no longer necessary to produce instances of this class, which makes testing more difficult, and you cannot generate multiple instances of different dependent environments for a given class, depending on the injection method. This static field is implicitly shared, And is a global state, and spring does not recommend it.
Why can't the Bean's set method be static type when spring is injected?