Spring @PostConstruct vs. init-method attribute

前端 未结 6 907
攒了一身酷
攒了一身酷 2020-12-04 06:35

Is there any difference between using the @PostConstruct annotation and declaring the same method as init-method in Spring XML configuration?

6条回答
  •  余生分开走
    2020-12-04 07:19

    No practically I don't think there is any difference but there are priorities in the way they work. @PostConstruct, init-method are BeanPostProcessors.

    1. @PostConstruct is a JSR-250 annotation while init-method is Spring's way of having an initializing method.
    2. If you have a @PostConstruct method, this will be called first before the initializing methods are called.
    3. If your bean implements InitializingBean and overrides afterPropertiesSet , first @PostConstruct is called, then the afterPropertiesSet and then init-method.

    For more info you can check Spring's reference documentation.

    Before JSR 250 specs , usage of init-method in xml was preferred way , as it decouples java classes (beans) from any spring specific classes/annotations.So if you are building a library that does not need to be dependent on spring infrastructure beans then use of init-method was preferred.During creation method u can specify the method that needs to be called as initialization method.

    Now with introduction of JSR 250 specs in Java EE and spring support of these annotations , dependency on spring framework has been reduced to a certain extent.

    But i have to admit that addition of these things increase the readability of code.So there are pros and cons both approaches.

提交回复
热议问题