编程知识 cdmana.com

Application runner, initializingbean and @ postconstruct execution sequence in spring initialization

Spring Initialize it ApplicationRunner、InitializingBean、@PostConstruct The question of execution order

    • Preface
    • One 、ApplicationRunner Usage of interface
    • Two 、InitializingBean Usage of interface
    • 3、 ... and 、@PostConstruct Use of annotations
    • Three in Spring The execution sequence of the project startup :

Preface

Because we need to use it Spring Initial load of bean, such as Spring The context acquisition class should be loaded first , Classes that listen for what should be loaded after startup , So consider the order of precedence , So study ApplicationRunner、InitializingBean、@PostConstruct The order of execution of

One 、ApplicationRunner Usage of interface

ApplicationRunner : It's an interface , It defines a run(ApplicationArguments args) Method , We need to write a class to implement this interface , And implement the run(ApplicationArguments args) Method .

Two 、InitializingBean Usage of interface

InitializingBean Interface for bean Provides a way to initialize methods , It only includes afterPropertiesSet Method , All classes that inherit this interface , Initializing bean This method will be implemented when . Be careful , The best way to implement this interface is to add Spring Annotation injection for , such as @Component

3、 ... and 、@PostConstruct Use of annotations

If you want to complete some initialization operations when generating objects , However, these initialization operations depend on dependency injection , Then it can't be implemented in the constructor . So , have access to @PostConstruct Annotate a method to complete initialization ,@PostConstruct Annotated methods will be called automatically after dependency injection . priority : Constructor >> @Autowired >> @PostConstruct Please refer to :@PostConstruct Use of annotations

Three in Spring The execution sequence of the project startup :

Thus we can see that : @PostConstruct>InitializingBean>ApplicationRunner

So be careful when you use it , Improper use is easy to cause unknown problems !

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[The blank of writing memory]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224104023990c.html

Scroll to Top