BeanFactory Aware : Xml Bean Factory « Spring « Java Tutorial






File: context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
                http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="logging" class="LoggingBean"/>

    <bean class="ShutdownHookBean"/>

</beans>

File: Main.java

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

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

    factory.preInstantiateSingletons();
    LoggingBean lb = (LoggingBean) factory.getBean("logging");
    lb.run();
  }

}

class LoggingBean implements BeanNameAware {
  private String name;

  public void setBeanName(String name) {
    this.name = name;
  }

  public void run() {
    System.out.println("Bean name is'" + this.name + "'.");
  }
}
class ShutdownHookBean implements BeanFactoryAware, Runnable {
  private ConfigurableListableBeanFactory beanFactory;

  public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
      if (beanFactory instanceof DefaultListableBeanFactory) {
          this.beanFactory = (ConfigurableListableBeanFactory)beanFactory;
          Runtime.getRuntime().addShutdownHook(new Thread(this));
      }
  }

  public void run() {
      if (this.beanFactory != null) {
          System.out.println("Destroying singletons.");
          this.beanFactory.destroySingletons();
      }
  }
}
  Download:  Spring-BeanFactoryAware.zip( 2,599 k)








28.6.Xml Bean Factory
28.6.1.Xml Bean Factory Demo
28.6.2.Static Factory
28.6.3.Compare Beans From Factory Bean
28.6.4.Create XmlBeanFactory from ClassPathResource
28.6.5.BeanFactory Aware
28.6.6.Non Static Factory
28.6.7.Hierarchical BeanFactory Demo
28.6.8.Add BeanFactory PostProcessor To XmlBeanFactory
28.6.9.Add addBeanPostProcessor To XmlBeanFactory