如何獲得spring上下文的方法總結
阿新 • • 發佈:2020-04-20
一 前言
打算重溫spring,以後可能每週會發一篇吧,有空就搞搞;
二 獲取上下文的幾種方式
- AnnotationConfigApplicationContext:從一個或多個基於Java的配置類中載入Spring應用上下文。
- AnnotationConfigWebApplicationContext:從一個或多個基於Java的配置類中載入Spring Web應用上下文。
- ClassPathXmlApplicationContext:從類路徑下的一個或多個XML配置檔案中載入上下文定義。
- FileSystemXmlapplicationcontext:從檔案系統下的一個或多個XML配置檔案中載入上下文定義。
- XmlWebApplicationContext:從Web應用下的一個或多個XML配置檔案中載入上下文定義
2.1 準備工作
被單實體
public class Sheet { // 顏色 private String color; // 長度 private String length; // 省略 set get }
sheet.xml 裡面注入了Bean Sheet,並且預設初始化 color值為red;
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="sheet" class="com.zszxz.bean.Sheet"> <property name="color" value="pink"></property> </bean> </beans>
2.2FileSystemXmlapplicationcontext 獲取上下文
FileSystemXmlApplicationContext 構造器引數中需要指定sheet.xml具體檔案系統路徑;獲得上下文之後再通過getBean方法獲取Bean Sheet; 拿到物件後使用getColor 方法列印顏色,為pink;
public static void main(String[] args) { // xml路徑 String path = "C:\\java\\workspaceforresource\\study-spring\\obtain-bean-way\\src\\main\\resources\\sheet.xml"; // 從檔案系統中獲取上下文 ApplicationContext applicationContext = new FileSystemXmlApplicationContext(path); // 獲取bean Sheet sheet = (Sheet) applicationContext.getBean("sheet"); // pink System.out.println(sheet.getColor()); }
2.3ClassPathXmlApplicationContext獲取上下文
ClassPathXmlApplicationContext 傳入引數是類路徑下sheet.xml的路徑;
public static void main(String[] args) { // 獲取上下文 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("sheet.xml"); // 獲得例項 Sheet sheet = (Sheet) applicationContext.getBean("sheet"); // pink System.out.println(sheet.getColor()); }
2.4AnnotationConfigApplicationContext獲取上下文
AnnotationConfigApplicationContext 獲取上下文,是通過java配置的方式獲取上下文;知識追尋者這邊需要進行java配置,內容如下,等同於之前的sheet.xml
/** * @Author lsc * <p> sheet配置類等同於sheet.xml</p> */ @Configuration public class SeetConfig { // 往配置類中注入Bean @Bean public Sheet sheet(){ // 建立物件 Sheet sheet = new Sheet(); // 設定屬性 sheet.setColor("pink"); return sheet; } }
獲取方式如下,傳入AnnotationConfigApplicationContext 引數是SeetConfig.class
public static void main(String[] args) { // 獲取上下文 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SeetConfig.class); // 獲得例項 Sheet sheet = (Sheet) applicationContext.getBean("sheet"); // pink System.out.println(sheet.getColor()); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。