Spring – Bean Lifecycle | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

This image has an empty alt attribute; its file name is image-1.png

Spring Tutorial Index Page: Link

  • IOC first create object of defined class then it will inject values into properties and then it will call init (afterPropertiesSet(), method defined in init-method, method with @PostConstruct) method.
  • To implement life cycle methods here we have 3 approaches

1. Programmatically approach

  • To implement lifecycle methods in Programmatically approach your POJO class need to implement from InitializingBean and DisposableBean.
  • InitializingBean -> afterPropertiesSet() called after injecting properties using setter or constructor.
  • DisposableBean -> destroy() called when container shutdown or destroy.

2. XML file approach

  • In Programmatically approach we must have to use abstract (afterPropertiesSet() and destroy()) methods but in XML file approach we can declare and use any methods but we have to configure these methods in XML file.
  • Use init-method and destroy-method attribute in <bean> tag.
  • Lets say we have 100 classes and in all classes we want init method and destroy method and also we declare same name method in all beans use of init-method and destroy-method will take time and also it is not good approach so in this scenario we can use default-init-method and default-destroy-method attributes in <beans> tag.

3. Annotation approach

  • Define any 2 methods and on top of method we have to use @PostConstruct on top of init method and @PreDestroy on top of destroy method.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s