日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

怎么随时获取Spring的上下文ApplicaitonContext,和Spring管理的Bean

發布時間:2025/4/16 69 豆豆
生活随笔 收集整理的這篇文章主要介紹了 怎么随时获取Spring的上下文ApplicaitonContext,和Spring管理的Bean 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

BeanFactory接口

Interface BeanFactory

getBean

<T> T getBean(String?name,Class<T>?requiredType)throws BeansException
上面是Apring的bean工廠的接口(顧名思議 拿到Spring的Bean) 下面看它的一個實現類

ClassPathXmlApplicationContext(BeanFactory接口的一個實現類)

public ClassPathXmlApplicationContext(String?configLocation)throws BeansException
Create a new ClassPathXmlApplicationContext, loading the definitions from the given XML file and automatically refreshing the context.
構造方法的參數 是Spring Bean配置的xml路徑(src下面的路徑)
然后 我們就可以通過new 一個ClassPathXmlApplicationContext 然后調用BeanFactory的getBean()方法獲取Spring管理的Bean了?

上面只是通過API說了Spring獲取Bean的原理,然而工作中:

在平時代碼中 我們都是通過?@Autowired 來引入一個對象。也就是Spring的依賴注入。

不過使用依賴注入需要滿足兩個條件,注入類 和被注入類 都需要交給Spring去管理,也就是需要在Spring中配置Bean

但是開發中,有些工具類(或者實體類)是不需要在Spring中配置的,如果工具類里面 想引用Spring配置的Bean 應該怎么辦

解決辦法

自己用的時候主動去new。 不可取 自己new的類 沒有交給Spring去管理,如果類中 用到了Spring的一些注解功能 完全失效??

也不可能像上面API中 去通過XML拿(IO操作很費時間)

工作中使用ApplicationContextAware接口

先通過setApplicationContext獲取Spring的上下文

在通過applicationContext去獲取Spring管理的Bean

寫一個SpringContextUtils專門去獲取Spring管理的Bean。也就是說 被注入對象 可以不交給Spring管理,就可以獲取Spring管理的Bean

import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware;public class SpringContextUtils implements ApplicationContextAware { private static ApplicationContext applicationContext;/*** 如果實現了ApplicationContextAware接口,在Bean的實例化時會自動調用setApplicationContext()方法*/@Overridepublic void setApplicationContext(ApplicationContext applicationContext)throws BeansException {SpringContextUtils.applicationContext = applicationContext;}public static <T> T getBean(Class<T> clazz) {return applicationContext.getBean(clazz);}}

注意點

?SpringContextUtils必須在Spring中配置bean(也就是SpringContextUtils必須交給Spring管理) 不然?在Bean的實例化時不會自動調用setApplicationContext()方法

?SpringContextUtils中的ApplicationContext需要是static的

這樣 我們就可在任何代碼任何地方任何時候中取出ApplicaitonContext. 從而獲取Spring管理的Bean

轉載于:https://www.cnblogs.com/ssskkk/p/9178338.html

總結

以上是生活随笔為你收集整理的怎么随时获取Spring的上下文ApplicaitonContext,和Spring管理的Bean的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。