Spring - Initializing a Spring Bean
It is often required to run some custom code on initialization of a Spring bean. e.g. to check for mandatory properties or establish initial connections. Spring provides a few constructs to initialize the beans after they are injected with the properties.
This is a method level annotation, available through the standard Java extensions package. It should be applied to methods that need to be executed after the properties are injected to the beans. Spring supports this annotation for initialization.
In this post, we explored 3 ways to initialize a Spring bean. Check out a working example for initialization in this GitHub project.
@PostConstruct
This is a method level annotation, available through the standard Java extensions package. It should be applied to methods that need to be executed after the properties are injected to the beans. Spring supports this annotation for initialization.
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
is used for XML based bean configuration. It can be configured with a zero-parameter method to initialize the 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
is an interface with one single method viz. afterPropertiesSet
. Beans can implement this interface, and the method would be invoked after all the properties are set on the Bean. It is usually the least preferred method of initialization as it strongly 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 explored 3 ways to initialize a Spring bean. Check out a working example for initialization in this GitHub project.
Comments
Post a Comment