SpringBoot中組件無法被注入
1、描述問題
在SpringBoot中,無法通過注解@AutoWired來自動(dòng)綁定實(shí)體bean或者組件component。
2、解決問題
首先檢查自己的是否在實(shí)體類上加上了@Component這樣的注解,@ComponentScan可以掃描的有@Service、@Repository、@Componnet、@Controller、@RestController等注解的類。當(dāng)項(xiàng)目啟動(dòng)的時(shí)候,說明在Spring容器中已經(jīng)存在了這些組件,放我們請(qǐng)求綁定的時(shí)候,如@Autowired或者@Resourece時(shí),通過IOC,會(huì)自動(dòng)為我們添加一個(gè)對(duì)象到我們的當(dāng)前類中。
但當(dāng)我們這一切都做好了,卻發(fā)現(xiàn)依舊不能通過@AutoWired進(jìn)行綁定時(shí),我們需要考慮需要綁定的對(duì)象是否存在一個(gè)無參構(gòu)造函數(shù)(默認(rèn)有,但是會(huì)被其他有參構(gòu)造函數(shù)覆蓋掉),下面的注解是我使用Lombok的注解。@Data包含了屬性的Set/Get的方法,還有包括toString()、Equals()等。@NoArgsConstructor表示構(gòu)造無參函數(shù)。@AllArgsConstructor表示構(gòu)造全參函數(shù)。
有了無參構(gòu)造函數(shù),基本就可以進(jìn)行綁定,并且調(diào)用該對(duì)象的方法了。
3、總結(jié)問題
Spring通過DI(依賴注入)來實(shí)現(xiàn)IOC(控制反轉(zhuǎn))
常用的注入方式Spring容器有三種方式:
①構(gòu)造方法注入,②Set方法注入,③接口注入。
方法比較多,放我們熟悉一種的時(shí)候,不妨去學(xué)習(xí)其他的方法,三者的注入方式都有一定的適用場(chǎng)景,這也是知識(shí)從點(diǎn)到面的過程。
解決在@Component注入為null
package com.gblfy; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import javax.annotation.PostConstruct; import javax.annotation.Resource; /** * @author gblfy * @ClassNme BaseCommon */ @Component//關(guān)鍵點(diǎn) 1 為spring組件 public class BaseCommon { //添加所需ConfigParam的私有成員 @Resource private ConfigParam configParam; // 關(guān)鍵點(diǎn)2 靜態(tài)初使化 一個(gè)工具類 這樣是為了在spring初使化之前 private static BaseCommon baseCommon; //關(guān)鍵 3 通過@PostConstruct 和 @PreDestroy 方法 實(shí)現(xiàn)初始化和銷毀bean之前進(jìn)行的操作 @PostConstruct public void init() { baseCommon = this; // 初使化時(shí)將已靜態(tài)化的configParam實(shí)例化 baseCommon.configParam = this.configParam; } /** * @param serviceName * @throws Exception */ @Transactional public void logWebService(String serviceName) throws Exception { //關(guān)鍵點(diǎn) 4 調(diào)用時(shí)請(qǐng)使用 此類靜態(tài)變量 .對(duì)象 例如:baseCommon.configParam String params = baseCommon.configParam.getParams(serviceName); System.out.println("返回參數(shù)" + params); } }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/qq_38584262/article/details/97768063