解析Java中如何獲取Spring中配置的bean
一、什么是Spring?
Spring是一個輕量級的控制反轉(zhuǎn)(IoC)和面向切面(AOP)的容器框架
二、如何在程序中獲取Spring配置的bean呢?
方法一:在初始化時保存ApplicationContext對象
代碼:
ApplicationContext ac = new FileSystemXmlApplicationContex("applicationContext.xml");
ac.getBean("beanId");
說明:這種方式適用于采用Spring框架的獨(dú)立應(yīng)用程序,需要程序通過配置文件手工初始化Spring的情況。
方法二:通過Spring提供的工具類獲取ApplicationContext對象
代碼:
import org.springframework.web.context.support.WebApplicationContextUtils;
ApplicationContext ac1 = WebApplicationContextUtils
.getRequiredWebApplicationContext(ServletContext sc)
ApplicationContext ac2 = WebApplicationContextUtils
.getWebApplicationContext(ServletContext sc)
ac1.getBean("beanId");
ac2.getBean("beanId");
方法三:繼承自抽象類ApplicationObjectSupport
說明:抽象類ApplicationObjectSupport提供getApplicationContext()方法,可以方便的獲取到ApplicationContext。Spring初始化時,會通過該抽象類的setApplicationContext(ApplicationContext context)方法將ApplicationContext 對象注入。
方法四:繼承自抽象類WebApplicationObjectSupport
說明:類似方法三,調(diào)用getWebApplicationContext()獲取WebApplicationContext
方法五:實(shí)現(xiàn)接口ApplicationContextAware
說明:實(shí)現(xiàn)該接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 對象。Spring初始化時,會通過該方法將ApplicationContext 對象注入。
相關(guān)文章
使用@RequestBody 接收復(fù)雜實(shí)體類集合
這篇文章主要介紹了使用@RequestBody 接收復(fù)雜實(shí)體類集合方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10Java Scala偏函數(shù)與偏應(yīng)用函數(shù)超詳細(xì)講解
Scala是一種多范式的編程語言,支持面向?qū)ο蠛秃瘮?shù)式編程。Scala也支持異常處理,即在程序運(yùn)行過程中發(fā)生意外或錯誤時,采取相應(yīng)的措施2023-04-04Java啟用Azure Linux虛擬機(jī)診斷設(shè)置
這篇文章主要介紹了Java啟用Azure Linux虛擬機(jī)診斷設(shè)置,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-05-05Java中常見的日期操作(取值、轉(zhuǎn)換、加減、比較)
本文給大家介紹java中常見的日期操作,日期取值、日期轉(zhuǎn)換、日期加減、日期比較,對java日期操作相關(guān)知識感興趣的朋友一起學(xué)習(xí)吧2015-12-12