We will use the same Ch02_Bean_Life_Cycle project that we developed in Case1.
Follow these steps:
- Add a Demo_InitializingBean class in the com.ch02.beans package, which implements the InitializingBean interface, as shown in the following piece of code:
public class Demo_InitializingBean implements InitializingBean { private String message; private String name; public Demo_InitializingBean() { // TODO Auto-generated constructor stub System.out.println("constructor gets called for initializing data members in demo Initializing bean"); message="welcome!!!"; name="no name"; } @Override public String toString() { // TODO Auto-generated method stub return message+" "+name; } }
- Override the afterPropertiesSet() method to process properties as follows:
@Override public void afterPropertiesSet() throws Exception { // TODO Auto-generated method stub name="Mr."+name.toUpperCase(); System.out.println("after properties Set got called"); }
- Add one more bean to the beans_life cycle.xml file, as shown in the following lines of code:
<bean id="obj_Initializing" class="com.ch02.beans.Demo_InitializingBean"/>
You can observe that we don't have to override any init-method attribute here as we did in Case1, as afterPropertiesSet() gets a call by the callback mechanism once the properties get set.
- Create a Test_InitializingBean class with the main method as shown in the following code snippet:
public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context=new ClassPathXmlApplicationContext("beans_lifecycle.xml"); Demo_InitializingBean obj= (Demo_InitializingBean) context.getBean("obj_Initializing"); System.out.println(obj); }
- The execution of the output is shown as follows:
In the preceding output, the underlined statements are not related to the newly configured bean. However, as the container does the initialization of all the beans configured, it will initialize the Demo_Custom_Init bean as well.