134

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

approxiblue
  • 6,982
  • 16
  • 51
  • 59
Jan Zyka
  • 17,460
  • 16
  • 70
  • 118

6 Answers6

195

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.

whysoseriousson
  • 196
  • 2
  • 16
Aravind A
  • 9,507
  • 4
  • 36
  • 45
  • 32
    If a bean is using more than one of those methods and relying on the order of initialization, it's going to be horribly complex and unmaintainable. – Donal Fellows Dec 15 '11 at 11:25
  • 2
    @Donal Quite true . Was just providing info on how this works. – Aravind A Dec 15 '11 at 11:32
  • 2
    There is an important difference: You need to specifically configure Spring to process annotations to make @PostConstruct work : http://stackoverflow.com/q/3434377/134898 – Juan Calero Dec 12 '14 at 08:50
  • `@PostConstruct` is from the package `javax.annotation` - which is deprecated in java 9 and removed in java 11. So, to use it, you should add additional dependency now. – Oleksandr Papchenko Apr 11 '19 at 16:39
21

There's no real difference. It's down to how you prefer to configure your system, and that's a matter of personal choice. Myself, I prefer to use @PostConstruct annotations for my own code (as the bean is only correctly configured after the method is called) and I use init-method when instantiating beans from non-Spring-aware libraries (can't apply annotations there, of course!) but I can totally understand people wanting to do it all one way or the other.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
6

@postconstruct is not part of the spring. It is part of javax package. Both are the same. using init-method we need to added in xml file.If you use @postconstruct adding in xml is not required. Check out the below article .

http://answersz.com/spring-postconstruct-and-predestroy/

Amruth M Raj
  • 61
  • 1
  • 2
6

Full code here: https://github.com/wkaczurba/so8519187 (spring-boot)

Using annotations:

@Slf4j
@Component
public class MyComponent implements InitializingBean {

    @Value("${mycomponent.value:Magic}")
    public String value;

    public MyComponent() {
        log.info("MyComponent in constructor: [{}]", value); // (0) displays: Null
    }

    @PostConstruct
    public void postConstruct() {
        log.info("MyComponent in postConstruct: [{}]", value); // (1) displays: Magic
    }

    @Override // init-method; overrides InitializingBean.afterPropertiesSet()
    public void afterPropertiesSet() {
        log.info("MyComponent in afterPropertiesSet: [{}]", value);  // (2) displays: Magic
    }   

    @PreDestroy
    public void preDestroy() {
        log.info("MyComponent in preDestroy: [{}]", value); // (3) displays: Magic
    }
}

Gets us:

Refreshing org.springframework.context...

MyComponent in constructor: [null]
MyComponent in postConstruct: [Magic]
MyComponent in afterPropertiesSet: [Magic]
...

Registering beans for JMX exposure on startup
Started DemoApplication in 0.561 seconds (JVM running for 1.011)
Closing org.springframework.context... Unregistering JMX-exposed beans on shutdown

...
MyComponent in preDestroy: [Magic]

Witold Kaczurba
  • 9,845
  • 3
  • 58
  • 67
4

There might be difference between @PostConstruct and init-method because @PostConstruct is handled in the postProcessAfterInitialization phase of bean initialization (AbstractAutowireCapableBeanFactory.initializeBean() method) by CommonAnnotationBeanPostProcessor, while init method gets called after the completion of postProcessBeforeInitialization phase (and, for this matter, before the beginning of postProcessAfterInitialization phase).
EDIT: So, the sequence is: 1) postProcessBeforeInitialization phase, 2) init method gets called, 3) postProcessAfterInitialization phase, which calls @PostConstruct method

(As a side note, a statement from the accepted answer

@PostConstruct, init-method are BeanPostProcessors

is not quite correct: @PostConstruct is handled by a BeanPostProcessor, init method is not.)

There will be difference if some (potentially custom) BeanPostProcessor, which is configured with (Ordered.getOrder()) to be executed after CommonAnnotationBeanPostProcessor, is doing something serious in its postProcessBeforeInitialization method.
There is no any difference with the default Spring configuration of BeanPostProcessors because all the BeanPostProcessors which are configured to be executed after CommonAnnotationBeanPostProcessor, don't do anything in postProcessBeforeInitialization method.

In conclusion, the accepted answer and the similar are right ... in 99% of the cases, and this post is just to pay a tribute to a concept "devil is in the details"

igor.zh
  • 1,410
  • 15
  • 19
  • Hi! This is confusing, if PostConstruct runs before init-method, how is it handled by the postProcessAfterInitialization if init method runs after postProcessBeforeInitialization and before postProcessAfterInitialization??? – Maxrunner Dec 04 '19 at 13:36
  • @Maxrunner, sorry for the confusion and many thanks for letting know! In fact, I never meant to say that PostConstruct runs before init-method. Anyway, I updated my answer with some clarifications – igor.zh Dec 05 '19 at 21:25
4

As you can see in the below diagram of Bean Creation Life-Cycle Callback.

Bean Creation Life-Cycle Callback

This 3 step happens in the Bean Creation Life-Cycle Callback:

  1. It is mentioned that @PostConstruct will be called.
  2. If InitializingBean is implemented, then afterPropertiesSet() will be called.
  3. If bean definition contains init-method or @Bean(initmethod="..") then it calls the init method.

This diagram is from Pro Spring 5: An In-Depth Guide to the Spring Framework and Its Tools

yashjain12yj
  • 723
  • 7
  • 19