本文的相關了解,是基于以下部落客文章以及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>