Java – spring: init method, postconstruct, afterpropertieset: when to use others?

There are many initialization options available in the spring bean lifecycle

Init method, postconstruct annotation, afterpropertieset, bean post initialization and class constructor All of these can be used to initialize beans

When I use these more than others, I feel confused In addition, is there a case where we might need to use all these options in a single bean? If so, it would be good to ask for instructions

I really look forward to getting some good answers

Solution

The difference between using the constructor and other options is that the constructor code is the first code to be executed, while other options are called only after the dependency is injected into the bean (from @ Autowired comments or XML files)

The code you write in the constructor will run when the bean's properties have not been started All @ Autowired fields will be null Sometimes this is what you want, but usually you want the code to run after the properties are set

Besides, I can't see any difference in other execution sequences I don't think there is a case where you want all the options in the same class

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>