Thursday, 8 February 2018

How to use life cycle of beans using annotations ?


You can use annotations :
@PostConstruct : called after bean is initialize
@PreDestroy : called before bean will destroy


@Autowired 
private Shape line;

static {
  ....
}

{
  ....
}

// Constructor
public Drawing() {
        System.out.println("Object of line in constructor : " + line);

}

@PostConstruct
private void init() {
        System.out.println("Initializing ***");

        System.out.println("Object of line in callback init : " + line);
}


@PreDestroy
private void destroy() {
        System.out.println("Destroying ***");
}


Inside constructor, you will get null for line object because the dependencies are not resolved in constructor.

ORDER : static block -> block -> constructor -> Spring callback

We have other alternatives like, implements InitializingBean, DIsposableBean of Spring.
But preferred are the above annotations because they exists in javax (JEE) - Framework independent.



No comments:

Post a Comment

Note: only a member of this blog may post a comment.