解析Java中如何獲取Spring中配置的bean
一、什么是Spring?
Spring是一個輕量級的控制反轉(zhuǎn)(IoC)和面向切面(AOP)的容器框架
二、如何在程序中獲取Spring配置的bean呢?
方法一:在初始化時保存ApplicationContext對象
代碼:
ApplicationContext ac = new FileSystemXmlApplicationContex("applicationContext.xml");
ac.getBean("beanId");
說明:這種方式適用于采用Spring框架的獨立應用程序,需要程序通過配置文件手工初始化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
方法五:實現(xiàn)接口ApplicationContextAware
說明:實現(xiàn)該接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 對象。Spring初始化時,會通過該方法將ApplicationContext 對象注入。
相關(guān)文章
Java Scala偏函數(shù)與偏應用函數(shù)超詳細講解
Scala是一種多范式的編程語言,支持面向?qū)ο蠛秃瘮?shù)式編程。Scala也支持異常處理,即在程序運行過程中發(fā)生意外或錯誤時,采取相應的措施2023-04-04Java中常見的日期操作(取值、轉(zhuǎn)換、加減、比較)
本文給大家介紹java中常見的日期操作,日期取值、日期轉(zhuǎn)換、日期加減、日期比較,對java日期操作相關(guān)知識感興趣的朋友一起學習吧2015-12-12