Why can't the set method of a bean be of static type when injected by spring?

Static methods belong to classes, and common methods belong to entity objects (that is, objects from New). Spring injection instantiates objects in containers, so static methods cannot be used.
 
In springframework, we cannot @Autowired a static variable to make it a spring bean, for example:
[java] 
  1. @Autowired  
  2. private static YourClass yourClass;  


You can try, yourClass cannot be dependency injected in this state, and a runtime exception java.lang.NullPointerException will be thrown. Why? Static variables/class variables are not properties of objects, but properties of a class. Spring is It is based on dependency injection at the object level.

The use of static variables/class variables expands the scope of use of static methods. Static methods are not recommended in spring. The main purpose of dependency injection is to allow the container to generate an instance of an object, Then use them throughout the life cycle, and also make testing easier.

Once you use static methods, you no longer need to generate instances of the class, which makes testing more difficult, and you can't give a A given class relies on injection to generate multiple instances with different dependency environments. This static field is implicitly shared and is a global global state, which is also not recommended by spring.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325124047&siteId=291194637