Want to initialize some static variables (checked out from the database) when the project starts
The first thought is to use static{ } static code blocks, but the execution order of static code blocks is before the Service layer injected by @Autowired.
That is to say, to access the database in the static code block, but when the code in the static code block is executed, @Autowired has not been injected, and NullPoint will be reported.
I searched for some solutions on the Internet. The following solutions can be solved. Others have not been tested for the time being:
private static List<ResourceEntity> resourceList = null; //initialized global static variable @Autowired private ResourceService resourceServiceTemp; private static ResourceService resourceService; //Literally, this annotation means to execute after the construction method (there is also a PreConstruct method) @PostConstruct public void init() { //This method will be executed automatically after the program starts resourceService = resourceServiceTemp; //Reassign the injected object to the static object resourceList = resourceService.findAll(); //You can call the method of Service here }