本篇文章給大家分享的是有關(guān)springboot中怎么利用上下文獲取bean,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
問題
在使用springboot開發(fā)項(xiàng)目過程中,有些時(shí)候可能出現(xiàn)說會(huì)有在spring容器加載前就需要注入bean的類,這個(gè)時(shí)候如果直接使用@Autowire注解,則會(huì)出現(xiàn)控制針異常!
解決辦法
如下:
創(chuàng)建一個(gè)springContextUtil類
package cn.eangaie.appcloud.util;import org.springframework.context.ApplicationContext;public class SpringContextUtil { private static ApplicationContext applicationContext; //獲取上下文 public static ApplicationContext getApplicationContext() { return applicationContext; } //設(shè)置上下文 public static void setApplicationContext(ApplicationContext applicationContext) { SpringContextUtil.applicationContext = applicationContext; } //通過名字獲取上下文中的bean public static Object getBean(String name){ return applicationContext.getBean(name); } //通過類型獲取上下文中的bean public static Object getBean(Class<?> requiredType){ return applicationContext.getBean(requiredType); }}
在AppcloudApplication.class 啟動(dòng)類里邊,將初始化該類,并將context注入進(jìn)去
public class AppcloudApplication { public static void main(String[] args) { ApplicationContext context=SpringApplication.run(AppcloudApplication.class, args); SpringContextUtil.setApplicationContext(context); }}
在需要注入bean的地方,使用getBean(bean名稱)的方式獲取
MessageTemplateController messageTemplateController= (MessageTemplateController) SpringContextUtil.getBean("messageTemplateController");
以上就是springboot中怎么利用上下文獲取bean,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
網(wǎng)站欄目:springboot中怎么利用上下文獲取bean-創(chuàng)新互聯(lián)
URL鏈接:http://aaarwkj.com/article12/gopdc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供用戶體驗(yàn)、ChatGPT、網(wǎng)站導(dǎo)航、網(wǎng)站制作、搜索引擎優(yōu)化、做網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容