關於springboot工具類中@Autowired注入bean,用static直接修飾,靜態方法使用bean時報空指針異常錯誤


 錯誤場景:

springboot + mybatis 

在工具類的靜態方法中,需要使用mapper(其他bean也一樣),所以最開始直接使用@Autowired進行了注入,代碼如下:

    @Autowired
    private static Mt4UsersMapper mt4UsersMapper;

    @Autowired
    private static UserBankAccountsMapper userBankAccountsMapper;
   
    @Autowired
    private static UserProfilesMapper userProfilesMapper;

接着在下面的靜態方法中直接進行了使用,查詢數據表(sql語句、數據庫數據都正常,理論上是可以查出數據的),然而報了下面的空指針錯誤:

看了相關資料了解到,這樣是無法注入成功的,所以無論你怎么查詢都是null,要想在非spring管理下的普通類中注入bean,不能直接用@Autowired進行注入,看了幾種辦法,這里就只記錄一種我認為最簡單的@PostConstruct的方式注入的吧 QAQ:

@Component
public class CreateReportTemFileUtil2 {
    @Autowired
    private Mt4UsersMapper testmt4UsersMapper;
    private static Mt4UsersMapper mt4UsersMapper;

    @Autowired
    private UserBankAccountsMapper testuserBankAccountsMapper;
    private static UserBankAccountsMapper userBankAccountsMapper;

    @Autowired
    private UserProfilesMapper testuserProfilesMapper;
    private static UserProfilesMapper userProfilesMapper;

    @PostConstruct
    public void init(){
        mt4UsersMapper = this.testmt4UsersMapper;
        userBankAccountsMapper = this.testuserBankAccountsMapper;
        userProfilesMapper = this.testuserProfilesMapper;
    }
}

划重點注解也很重要。

 

這樣就注入成功啦!!后面代碼直接跑通了,不再一直報空指針異常了,這個方法 不用再新建一個類什么的,感覺還是方便。當然這也是有一定局限性的,因為mapper那邊是加了@Repository的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM