现在的位置: 首页 > 综合 > 正文

Spring之BeanFactory与ApplicationConText区别

2013年03月25日 ⁄ 综合 ⁄ 共 793字 ⁄ 字号 评论关闭

使用BeanFactory从xml配置文件加载bean: 

  1. import org.springframework.beans.factory.xml.XmlBeanFactory;
  2. import org.springframework.core.io.FileSystemResource;
  3. public class XmlConfigWithBeanFactory {
  4.     public static void main(String[] args) {
  5.         XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource(
  6.                 "build/beans.xml"));
  7.     }
  8. } 

使用ApplicationConText从xml配置文件加载bean:

 

  1. public class XmlConfigWithApplication{
  2.     public static void main(String[] args){
  3.         ApplicationContext application = new ClassPathXmlApplicationContext(beans.xml"));
  4.          application.getBean("BeanName");
  5.     }
  6. }

ApplicationContext和BeanFacotry相比,提供了更多的扩展功能,但其主要区别在于后者是延迟加载,如果Bean的某一个属性没有注入,BeanFacotry加载后,直至第一次使用调用getBean方法才会抛出异常;而ApplicationContext则在初始化自身时检验,这样有利于检查所依赖属性是否注入;所以通常情况下我们选择使用ApplicationContext.

抱歉!评论已关闭.