在項目中有時需要根據需要在自己new一個對象,或者在某些util方法或屬性中獲取Spring Bean對象,從而完成某些工作,但是由於自己new的對象和util方法並不是受Spring所管理的,如果直接在所依賴的屬性上使用@Autowired就會報無法注入的錯誤,或者是沒報錯,但是使用的時候會報空指針異常。總而言之由於其是不受Spring IoC容器所管理的,因而無法注入。

Spring的核心是ApplicationContext,它負責管理 beans 的完整生命周期。我們可以從applicationContext里通過bean名稱獲取注入的bean,然後進行操作。

SpringContextUtil工具類的代碼如下所示:
package com.rickie.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
public class SpringContextUtil {
private static ApplicationContext applicationContext;
// 設置上下文
public static void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
// 獲取上下文
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
// 通過名字獲取上下文中的bean
public static Object getBean(String name) {
if(name == null || name.length()==0) {
return null;
}
try {
String beanName = “”;
if(name.length() >1){
beanName = name.substring(0, 1).toLowerCase() + name.substring(1);
} else {
beanName = name.toLowerCase();
}
return applicationContext.getBean(beanName);
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
// 通過類型獲取上下文中的bean
public static <T> T getBean(Class<T> clazz) {
try {
return (T) applicationContext.getBean(clazz);
} catch(Exception ex) {
ex.printStackTrace();
return null;
}
}
}
由於該類並沒有實現ApplicationContextAware接口,因此先設置好ApplicationContext的值。可以在Spring Boot的啟動方法main中進行設置:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args);
SpringContextUtil.setApplicationContext(ctx);
}
}
在Spring Boot的啟動時調用的run方法會返回一個
ConfigurableApplicationContext,將其設置到SpringContextUtil的靜態屬性中,然後能夠通過ApplicationContext對象獲取到需要使用的bean,這樣就可以使用了。

下面是一段使用SpringContextUtil工具類的示例代碼:
/**
* 創建一個新的客戶
* @param customer
* @return
*/
public int create(Customer customer) {
if(this.customerGateway == null) {
this.customerGateway = SpringContextUtil.getBean(CustomerGateway.class);
}
return customerGateway.insert(customer);
}
這樣,無論是在靜態方法中,還是在手動new的實例中,我們都能夠成功獲取IoC容器所管理的bean。如果我們想在靜態屬性中獲取Spring Bean,其實也非常簡單,直接對屬性賦值即可,如下所示:
private static Customer customer = SpringBeanUtil.getBean(Customer.class);

Spring Cloud Alibaba微服務實戰技術專欄,從項目實踐出發,包括Spring Cloud Alibaba、Nacos、Gateway、Sentinel、Log日誌、分佈式全局唯一ID、DDD領域驅動設計等等技術內容,可幫助你對Spring Cloud 微服務技術棧有更加全面和直觀的了解。相信你通過本專欄的練習和實踐,能夠學以致用,提升微服務應用的開發能力。
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/230969.html