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

View: 20361|Reply: 0

[Source] Java annotates the difference between @PostConstruct and static constructors

[Copy link]
Posted on 2021-7-30 10:48:11 | | | |
Recently, I came across this annotation in a company project @PostConstruct and I was puzzled.

Review:

Java annotations@PostConstruct and detailed explanations and examples of @PreDestroy
https://www.itsvse.com/thread-7386-1-1.html


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:







Previous:Docker Installs Redis Visual Management Tool (redis-manager)
Next:Kafka's auto.offset.reset value is explained in detail
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