關(guān)于Springboot如何獲取IOC容器
在Springboot項(xiàng)目中如果要獲取IOC容器目前有兩種方法。
方法一(不實(shí)用,不推薦):在Springboot項(xiàng)目中都會(huì)存在一個(gè)SpringApplication的啟動(dòng)類,我們通過以下代碼啟動(dòng)IOC容器。
SpringApplication.run(Application.class, args);
其實(shí)run方法會(huì)將創(chuàng)建的IOC容器作為返回值返回,那么我們就可以通過聲明一個(gè)ApplicationContext對象來接收run方法的返回值。
public class SpringApplication { public static void main(String[] args) {ApplicationContext applicationContext = SpringApplication.run(Application.class, args);Object startSerive = applicationContext.getBean('startSerive'); }}
但是,使用這種方法會(huì)遇到各種各樣的問題,所以我們通常使用第二種方法。
方法二(強(qiáng)烈推薦):通過編寫實(shí)現(xiàn)了ApplicationContextAware的工具類來獲取IOC容器,當(dāng)實(shí)現(xiàn)了ApplicationContextAware的類在容器中被初始化和加載后,會(huì)自動(dòng)調(diào)用ApplicationContextAware中的setApplicationContext方法,將IOC容器傳入setApplicationContext方法的形參中。
以下是用于獲取IOC容器的工具類:
public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; public SpringContextUtil() { } /** * 設(shè)置上下文 * @param applicationContext * @throws BeansException */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {if (SpringContextUtil.applicationContext == null) { SpringContextUtil.applicationContext = applicationContext;} } /** * 獲取上下文 * @return */ public static ApplicationContext getApplicationContext() {return applicationContext; } /** * 通過名字獲取上下文中的bean * @param name * @return */ public static Object getBean(String name){return applicationContext.getBean(name); } /** * 通過類型獲取上下文中的bean * @param requiredType * @return */ public static Object getBean(Class<?> requiredType){return applicationContext.getBean(requiredType); }}
上面這個(gè)工具類只有在被IOC容器加載完之后才會(huì)調(diào)用setApplicationContext,那么該怎么把工具類放到IOC容器中呢?我們使用@Import注解來實(shí)現(xiàn),具體使用方法請看下面代碼:
@SpringBootApplication@Import({SpringContextUtil.class})public class Application { public static void main(String[] args) {SpringApplication.run(Application.class, args); }}
注:不使用@Import也是可以的,例如在SpringContextUtil類上面標(biāo)注@Component等類似的注解也是可以的。
@Import注解須知:
1.@Import只能用在類上 ,@Import通過快速導(dǎo)入的方式實(shí)現(xiàn)把實(shí)例加入spring的IOC容器中
2.加入IOC容器的方式有很多種,@Import注解可以用于導(dǎo)入第三方包 ,當(dāng)然@Bean注解也可以,但是@Import注解快速導(dǎo)入的方式更加便捷
總結(jié)本篇文章就到這里了,希望能給你帶來幫助,也希望您能夠多多關(guān)注好吧啦網(wǎng)的更多內(nèi)容!
相關(guān)文章:
1. 編程語言PHP在Web開發(fā)領(lǐng)域的優(yōu)勢在哪?2. 詳解Android studio 動(dòng)態(tài)fragment的用法3. 圖文詳解vue中proto文件的函數(shù)調(diào)用4. 什么是python的自省5. 基于android studio的layout的xml文件的創(chuàng)建方式6. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁效果(實(shí)例代碼)7. 解決Android studio xml界面無法預(yù)覽問題8. Android如何加載Base64編碼格式圖片9. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)10. Springboot Druid 自定義加密數(shù)據(jù)庫密碼的幾種方案

網(wǎng)公網(wǎng)安備