About initializing a static variable in Spring (you need to call the Service layer and then check it out from the database)

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
        }


Guess you like

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