Spring ApplicationContext 容器
-
Application Context 是 BeanFactory 的子接口,也被称为 Spring 上下文环境。
-
Application Context 是 spring 中较高级的容器。和 BeanFactory 类似,它可以加载配置文件中定义的 bean,将所有的 bean 集中在一起,当有请求的时候分配 bean。 另外,它增加了企业所需要的功能,比如,从属性文件中解析文本信息和将事件传递给所指定的监听器。这个容器在 org.springframework.context.ApplicationContext interface 接口中定义。
-
ApplicationContext 包含 BeanFactory 所有的功能,一般情况下,相对于 BeanFactory,ApplicationContext 会更加优秀。
最常被使用的 ApplicationContext 接口实现:
-
FileSystemXmlApplicationContext:该容器从 XML 文件中加载已被定义的 bean。在这里,你需要提供给构造器 XML 文件的完整路径。
-
ClassPathXmlApplicationContext:该容器从 XML 文件中加载已被定义的 bean。在这里,你不需要提供 XML 文件的完整路径,只需正确配置 CLASSPATH 环境变量即可,因为,容器会从 CLASSPATH 中搜索 bean 配置文件。
-
WebXmlApplicationContext:该容器会在一个 web 应用程序的范围内加载在 XML 文件中已被定义的 bean。 我们已经在 Spring Hello World Example章节中看到过 ClassPathXmlApplicationContext 容器,并且,在基于 spring 的 web 应用程序这个独立的章节中,我们讨论了很多关于 XmlWebApplicationContext。所以,接下来,让我们看一个关于 FileSystemXmlApplicationContext 的例子。
我们用一个表格来说明下:
ApplicationContext常用实现类 | 作用 |
---|---|
AnnotationConfigApplicationContext | 从一个或多个基于java的配置类中加载上下文定义,适用于java注解的方式。 |
ClassPathXmlApplicationContext | 从类路径下的一个或多个xml配置文件中加载上下文定义,适用于xml配置的方式。 |
FileSystemXmlApplicationContext | 从文件系统下的一个或多个xml配置文件中加载上下文定义,也就是说系统盘符中加载xml配置文件。 |
AnnotationConfigWebApplicationContext | 专门为web应用准备的,适用于注解方式。 |
XmlWebApplicationContext | 从web应用下的一个或多个xml配置文件加载上下文定义,适用于xml配置方式。 |
ApplicationContext还有额外的功能
- 默认初始化所有的Singleton,也可以通过配置取消预初始化。
- 继承MessageSource,因此支持国际化。
- 资源访问,比如访问URL和文件。
- 事件机制。
- 同时加载多个配置文件。
- 以声明式方式启动并创建Spring容器。
这里特别说明下:
-
默认全部加载所有bean
由于ApplicationContext会预先初始化所有的Singleton Bean,于是在系统创建前期会有较大的系统开销, 但一旦ApplicationContext初始化完成,程序后面获取Singleton Bean实例时候将有较好的性能。
-
对于加载比较重并且没有立即使用的可以懒加载
通过为bean设置lazy-init属性为true,即Spring容器将不会预先初始化该bean。
非 Spring 容器下获取bean
@Component
public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext mSpringContext;
public static ApplicationContext getContext() {
return mSpringContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(Class<?> clazz) {
return (T) mSpringContext.getBean(clazz);
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name)
{
return (T) mSpringContext.getBean(name);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
mSpringContext = applicationContext;
}
}
示例代码
比如Spring 容器有个 UserService,
public class Test
{
public void test()
{
UserService us = SpringContextUtils.getBean(UserService.cllass);
}
}
这个可以很常用的哦