spring ioc
BeanFactory接口
是Spring Bean IOC容器的顶级接口,负责读取bean配置文档,管理bean的加载,实例化,维护bean之间的依赖关系,负责bean的生命周期 ,客户若想获取一个实例,必须要借助这个对象,该接口提供以下基本方法供获取Bean相关信息。
Object getBean(String name) throws BeansException;
Object getBean(String name, Class requiredType) throws BeansException;
Object getBean(String name, Object[] args) throws BeansException;
Class getType(String name) throws NoSuchBeanDefinitionException;
String[] getAliases(String name);
boolean containsBean(String name);
#Bean是否是单例
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
#Bean是否是多例
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
BeanFactory的继承关系如下
BeanFactory | ListableBeanFactory(接口)
| ConfigurableListableBeanFactory(抽象类)
| DefaultListableBeanFactory
| XmlBeanFactory
| ApplicationContext | AutowireCapableBeanFactory(接口)
| AbstractAutowireCapableBeanFactory(抽象类)
| DefaultListableBeanFactory
| XmlBeanFactory
| ConfigurableListableBeanFactory(接口)
| DefaultListableBeanFactory
| XmlBeanFactory | HierarchicalBeanFactory(接口)
| ConfigurableBeanFactory
| ApplicationContext
1.ListableBeanFactory,Spring鼓励使用这个接口获取bean,其他几个都不鼓励用户使用,该接口提供了容器中bean迭代访问的功能,可以一次性获取全部的bean数量、所有bean的name等等。
2.AutowireCapableBeanFactory,可以使用这个接口集成其它框架,捆绑并填充并不由Spring管理生命周期并已存在的实例.像集成WebWork的Actions 和Tapestry Page就很实用.一般应用开发者不会使用这个接口。
3.HierarchicalBeanFactory, 提供父容器的访问功能.至于父容器的设置,需要找ConfigurableBeanFactory的setParentBeanFactory。
ApplicationContext接口
3)事件传递功能,通过实现ApplicationContextAware接口。
ApplicationContext | ConfigurableApplicationContext
| XmlWebApplicationContext
| ClassPathXmlApplicationContext
| FileSystemXmlApplicationContext
FileSystemXmlApplicationContext
从文件系统中获取XML配置文件,比如直接通过指定file:D:\applicationContext.xml
ClassPathXmlApplicationContext
从classpath下读取配置文件,比如classpath:applicationContext.xml
XmlWebApplicationContext
专门WEB应用准备的,直接通过CLASSPATH下面的配置文件,不需要再加上classpath前缀。 但需要有额外的配置。
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
这两种方式都默认配置文件为WEB-INF/applicationContext.xml,也可使用context-param指定配置文件
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
BeanFactory的用法
Resource resource = new FileSystemResource("beans.xml"); BeanFactory factory = new XmlBeanFactory(resource); ClassPathResource resource = new ClassPathResource("beans.xml"); BeanFactory factory = new XmlBeanFactory(resource);
ApplicationContext的用法
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"}); Car car = ctx.getBean("car",Car.class); ApplicationContext context = new FileSystemlXmlApplicationContext(new String[] {"applicationContext.xml"}); Driver car1 = ctx.getBean("driver",Driver.class);

浙公网安备 33010602011771号