本文的相关理解,是基于以下博主文章以及spring书籍总结而来
spring上下文 博客
文字型个人理解:https://www.cnblogs.com/chenbenbuyi/p/8166304.html
代码型技术解析:https://www.cnblogs.com/hello-shf/p/11006750.html
书籍:《Spring实战》第4版 P18-P19页 1.2.1 使用应用上下文
bean:spring 容器中的对象
spring 容器:负责管理bean 的生命周期
DI 依赖注入: 例如将B类所依赖的A类注入到B中,例如常用的:@Autowrite和@Resource 注解
BeanFactory:最简单的spring容器,只能提供基本的DI功能
应用上下文:(ApplicationContext) 继承了BeanFactory后派生而来的,是容器的一种,可以对bean进行管理操作
加载 应用上下文 的多种方式:
① AnnotationConfigApplicationContext:从一个或多个基于java的配置类中加载上下文定义,适用于java注解的方式;
② ClassPathXmlApplicationContext:从类路径下的一个或多个xml配置文件中加载上下文定义,适用于xml配置的方式;
③ FileSystemXmlApplicationContext:从文件系统下的一个或多个xml配置文件中加载上下文定义,也就是说系统盘符中加载xml配置文件;
④ AnnotationConfigWebApplicationContext:专门为web应用准备的,适用于注解方式;
⑤ XmlWebApplicationContext:从web应用下的一个或多个xml配置文件加载上下文定义,适用于xml配置方式。
例如:
1.创建一个xml文件,如:applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
//中间部分是你自己配置的所有bean
</beans>
2. 加载上下文 ,获取bean信息
public class Test {
public static void main(String[] args) {
//加载项目中的spring配置文件到容器
// ApplicationContext context = new ClassPathXmlApplicationContext("resouces/applicationContext.xml");
//加载系统盘中的配置文件到容器
ApplicationContext context = new FileSystemXmlApplicationContext("E:/Spring/applicationContext.xml");
//从容器中获取对象实例
Man man = context.getBean(Man.class);
man.driveCar();
}
}
或使用 web.xml 加载:
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>