This article is a mirror article of machine translation, please click here to jump to the original article.

View: 13053|Reply: 0

[Source] @Autowired annotations and static methods

[Copy link]
Posted on 2/27/2019 2:19:45 PM | | | |
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







Previous:Corel Products KeyGen 2019
Next:C*or*el 2019 product full series of keygens Chinese version [can be registered for the meeting 2019]
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com