Spring容器

来源:互联网 发布:人工智能电影内容 编辑:程序博客网 时间:2024/05/21 23:00

Spring容器最基本的接口是BeanFactory,用来配置、创建、管理Bean。BeanFactory还有一个子接口ApplictionContext,故也成为Spring上下文;

区别:

1.BeanFactory:ApplictionContext的父接口;

2.ApplictionContext:作为BeanFactory的子接口,其中方法要更为丰富一些;

3.BeanFactory创建Bean时,调用一个Bbean时生成一个对象;而使用ApplictionContext时,会将配置文件中的所有Bean生成对象;

4.因为Bean之间可能会存在一定的关联,所以使用BeanFactory时可能会出现一定的问题;强烈推荐使用ApplictionContext


1.使用BeanFactory获得Bean对象;

Resource  r = new ClassPathResource("beans.xml");DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions(r);Person p1 =  beanFactory.getBean("person",Person.class);p1.useCar();

2.使用ApplictionContext获得Bean对象;

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");Person p = ctx.getBean("person", Person.class);p.useCar();


0 0
原创粉丝点击