Spring 中常见的几个容器接口及具体的实现类
前言
Spring 内部提供了很多表示 Spring 容器的接口和对象,我们今天来看看几个比较常见的容器接口和具体的实现类。
BeanFactory 接口
该接口源码在此包下,有兴趣的童鞋和自行查阅了解。
org.springframework.beans.factory
Spring 容器中极具代表性的容器就是 BeanFactory 接口,该接口是Spring 容器的顶层接口,提供了容器的基本功能。
我们来分析下源码,看看常用的几个方法。
/**
* 按照 bean 的 name 查找容器中指定类型的 bean
* @param name the name of the bean to retrieve
* @return an instance of the bean
*/
Object getBean(String name) throws BeansException;
/**
* 这是一个泛型方法,按照 bean 的 name 查找容器中指定类型的 bean,
* 返回指定类型的 bean 对象。
* @param name the name of the bean to retrieve
* @param requiredType type the bean must match; can be an interface or superclass
* @return an instance of the bean
*/
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
/**
* 返回容器中指定类型的 bean 对象
* @param requiredType type the bean must match; can be an interface or superclass
* @return an instance of the bean
*/
<T> T getBean(Class<T> requiredType) throws BeansException;
/**
* 获取指定类型 bean 对象的获取器
* @param requiredType type the bean must match; can be an interface or superclass
* @return a corresponding provider handle
*/
<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);
ApplicationContext 接口
源码所在包:
org.springframework.context
该接口继承了 ListableBeanFactory和HierarchicalBeanFactory 这两个接口,而这两个接口又继承了 BeanFactory 接口,所以内部包含了 BeanFactory 的所有功能,并在其基础上进行了扩展,增加了很多功能,如 AOP、国际化等。
ClassPathXmlApplicationContext 类
源码所在包:
org.springframework.context.support
该类实现了 ApplicationContext 接口,这个类名称包含了 ClassPath Xml,说明这个容器类可以从 classpath 中加载 bean xml 配置文件,然后创建 xml 中配置的 bean 对象。
AnnotationConfigApplicationContext 类
源码所在包:
org.springframework.context.annotation
这个类也实现了 ApplicationContext 接口,注意其类名包含了 Annotation 和 config 两个单词,我们知道 bean 的定义支持 xml 的方式和注解的方式,当我们使用注解的方式定义bean的时候,就需要用到该容器来装载,该容器内部会解析注解来构建构建和管理需要的bean。
【注意】注解的方式相对于 xml 方式更方便一些,也是普遍比较推荐的方式。
- END -