Implements Initializing Bean : XML Bean Lifecycle « Spring « Java Tutorial






File: context.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
   <bean id="nameClass"
         class="InitializingBeanNameClass"/>
</beans>

File: Main.java

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class Main {

  public static void main(String[] args) throws Exception {
    BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("context.xml"));

    InitializingBeanNameClass nameClass = (InitializingBeanNameClass) beanFactory
        .getBean("nameClass");

    System.out.println(nameClass.getFirstName());
  }
}

class InitializingBeanNameClass implements InitializingBean {
  private String firstName;

  public String getFirstName() {
    return this.firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public void afterPropertiesSet() throws Exception {
    if (this.firstName == null) {
      throw new Exception("firstName property is required.");

    }
  }

}
  Download:  Spring-ImplementsInitializingBean.zip( 2,599 k)








28.7.XML Bean Lifecycle
28.7.1.destroy method
28.7.2.Custom Initialization Method
28.7.3.Bean Liftcycle Initializing
28.7.4.Bean Lifecycle Disposable Bean
28.7.5.Implements Initializing Bean
28.7.6.Implements Disposable Bean