从bean开始,Spring容器
2017-07-14 本文已影响0人
我弟是个程序员
先说bean的创建,在基于Spring的应用中,你的应用对象生存于Spring容器(container,即bean容器)中。Spring容器负责创建对象,装配它们,配置它们并管理它们的整个生命周期,从生存到死亡。Spring容器使用DI管理构成应用的组件,它会创建相互协作的组件之间的关联。Spring容器并不是只有一个。Spring自带了多个容器实现,可以归为两种不同的类型。bean工厂(由org.springframework. beans.factory.eanFactory接口定义)是最简单的容器,提供基本的DI支持。应用上下文(由org.springframework.context.ApplicationContext接口定义)基于BeanFactory构建,并提供应用框架级别的服务,例如从属性文件解析文本信息以及发布应用事件给感兴趣的事件监听者。
一般在应用中,应用上下文要比bean工厂更受欢迎。下面来看看使用 应用上下文:
Spring自带了多种类型的应用上下文:
- AnnotationConfigApplicationContext:从一个或多个基于Java的配置类中加载Spring应用上下文。
- AnnotationConfigWebApplicationContext:从一个或多个基于Java的配置类中加载Spring Web应用上下文。
- ClassPathXmlApplicationContext:从类路径下的一个或多个XML配置文件中加载上下文定义,把应用上下文的定义文件作为类资源。
- FileSystemXmlapplicationcontext:从文件系统下的一个或多个XML配置文件中加载上下文定义。
- XmlWebApplicationContext:从Web应用下的一个或多个XML配置文件中加载上下文定义。
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"/config/applicationContext.xml","/config/io.xml"}); //需要配置对应类路径下的配置xml文件
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);//需要配置java类注解
ApplicationContext context = new FileSystemXmlApplicationContext("D:/SpringJdbcDemo/src/jdbc.xml");//文件系统绝对路径来构建
以上不管是那种方式来装载应用上下文,将bean加载到bean工厂的过程都是相似的。
顺带下面贴出一张spring框架概览图,毕竟这是以后要学的东西:
