Spring中BeanFactory与ApplicationContext的差别

区别:
ApplicationContext和BeanFactory相比,提供了更多的扩展功能,但其主要区别在于BeanFactory是延迟加载,如果Bean的某一个属性没有注入,BeanFactory加载后,直至第一次使用getBean方法调用此Bean时才会抛出异常;而ApplicationContext则在初始化自身时检验,这样有利于检查所依赖属性是否注入;所以通常情况下我们选择使用ApplicationContext.
-----------------------------------------------------------------------------------------------------------------------------------
使用BeanFactory从xml配置文件加载bean:
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class BeanFactoryClient{
	
	public static void main(String[] args){
		BeanFactory beanFactory = new XmlBeanFactory(new FileSystemResource("beans.xml"));
		beanFactory.getBean("beanName");
	}
}


使用ApplicationContext从xml配置文件加载bean:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ApplicationContextClient{
	
	public static void main(String[] args) {
		ApplicationContext cxt = new ClassPathXmlApplicationContext("beans.xml");
		cxt.getBean("beanName");
	}
}

你可能感兴趣的:(java,spring,bean,xml)