Recently, I came across this annotation in a company project @PostConstruct and I was puzzled.
Review:
After consulting, the summary is as follows:
1. Starting from the Java EE5 specification, two annotations that affect the life cycle of the servlet, @PostConstruct and @PreDestroy, are used to modify a non-static void() method. There are two ways to write it:
@PostConstruct
public void someMethod(){}
or
public @PostConstruct void someMethod(){}
The @PostConstruct modified method runs when the server loads the servlet, andIt will only be executed once by the server。 PostConstruct is executed after the constructor and before the init() method. The PreDestroy() method executes after the destroy() method is intellectual
In addition, the order of Constructor, @Autowired, and @PostConstruct in spring
In fact, from the literal meaning of dependency injection, we can know that to inject object p into object A, then object A and object p must first be generated before the injection can be performed. So, if a member variable p is annotated @Autowried in class A, then @Autowired injection occurs after A's construction method is executed.
If you want to complete some initialization operations when generating an object, and these initialization operations depend on dependency injection, then you can't do it in the constructor. To do this, you can use a method @PostConstruct annotations to complete the initialization, @PostConstruct annotated methods will be automatically called after dependency injection is completed.
Constructor >> @Autowired >> @PostConstruct
Example:
|