Spring - Initializing a Spring Bean

In Spring, it's often necessary to run custom code during a bean's initialization—for example, to validate mandatory properties or establish initial connections. Spring offers several mechanisms to initialize beans after they’ve been injected with their properties.


@PostConstruct


This annotation is applied at the method level and is part of the standard Java extensions package. It should be used on methods that need to run after a bean's properties have been injected. Spring supports this annotation for initialization purposes.

import javax.annotation.PostConstruct;
import org.springframework.util.Assert;

public class UserService {

 private String userprops;
 
 public String getUserprops() {
  return userprops;
 }

 public void setUserprops(String userprops) {
  this.userprops = userprops;
 }

 @PostConstruct
 public void initWithPostConstuctor() {
  System.out.println("PostConstruct method called");
  Assert.notNull(userprops);
 }
}



init-method


init-method attribute is used in XML-based bean configuration and can be set to a zero-parameter method to initialize the bean.

<bean class="com.codelooru.pojo.UserService" id="userService" init-method="initWithXMLInitMethod">
    <property name="userprops" value="userprops">
    </property>
</bean>

import org.springframework.util.Assert;

public class UserService {

 private String userprops;
 
 public String getUserprops() {
  return userprops;
 }

 public void setUserprops(String userprops) {
  this.userprops = userprops;
 }

 public void initWithXMLInitMethod() {
  System.out.println("init-method called");
  Assert.notNull(userprops);
 }

}



InitializingBean


InitializingBean interface contains a single method, afterPropertiesSet, which beans can implement to execute code after all properties are set on the bean. This approach is generally the least preferred for initialization, as it tightly couples the class to Spring..

import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

public class UserService implements InitializingBean {

 private String userprops;
 
 public String getUserprops() {
  return userprops;
 }

 public void setUserprops(String userprops) {
  this.userprops = userprops;
 }

 public void afterPropertiesSet() throws Exception {
  System.out.println("afterPropertiesSet for InitializingBean called");
  Assert.notNull(userprops);
 }
}



Sample Code


In this post, we examined three methods for initializing a Spring bean. You can find a working example of the initialization process at this link GitHub project.