关于springboot工具类中@Autowired注入bean,用static直接修饰,静态方法使用bean时报空指针异常错误...
?錯(cuò)誤場(chǎng)景:
springboot + mybatis?
在工具類的靜態(tài)方法中,需要使用mapper(其他bean也一樣),所以最開(kāi)始直接使用@Autowired進(jìn)行了注入,代碼如下:
@Autowiredprivate static Mt4UsersMapper mt4UsersMapper;@Autowiredprivate static UserBankAccountsMapper userBankAccountsMapper;@Autowiredprivate static UserProfilesMapper userProfilesMapper;接著在下面的靜態(tài)方法中直接進(jìn)行了使用,查詢數(shù)據(jù)表(sql語(yǔ)句、數(shù)據(jù)庫(kù)數(shù)據(jù)都正常,理論上是可以查出數(shù)據(jù)的),然而報(bào)了下面的空指針錯(cuò)誤:
看了相關(guān)資料了解到,這樣是無(wú)法注入成功的,所以無(wú)論你怎么查詢都是null,要想在非spring管理下的普通類中注入bean,不能直接用@Autowired進(jìn)行注入,看了幾種辦法,這里就只記錄一種我認(rèn)為最簡(jiǎn)單的@PostConstruct的方式注入的吧 QAQ:
@Component public class CreateReportTemFileUtil2 {@Autowiredprivate Mt4UsersMapper testmt4UsersMapper;private static Mt4UsersMapper mt4UsersMapper;@Autowiredprivate UserBankAccountsMapper testuserBankAccountsMapper;private static UserBankAccountsMapper userBankAccountsMapper;@Autowiredprivate UserProfilesMapper testuserProfilesMapper;private static UserProfilesMapper userProfilesMapper;@PostConstructpublic void init(){mt4UsersMapper = this.testmt4UsersMapper;userBankAccountsMapper = this.testuserBankAccountsMapper;userProfilesMapper = this.testuserProfilesMapper;} }劃重點(diǎn)注解也很重要。
?
這樣就注入成功啦!!后面代碼直接跑通了,不再一直報(bào)空指針異常了,這個(gè)方法 不用再新建一個(gè)類什么的,感覺(jué)還是方便。當(dāng)然這也是有一定局限性的,因?yàn)閙apper那邊是加了@Repository的。
?
轉(zhuǎn)載于:https://www.cnblogs.com/xk920/p/10895025.html
總結(jié)
以上是生活随笔為你收集整理的关于springboot工具类中@Autowired注入bean,用static直接修饰,静态方法使用bean时报空指针异常错误...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Python 中的*args和**kwa
- 下一篇: MockServer jar包安装