日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

autowired 静态方法使用_关于springboot工具类中@Autowired注入bean,用static直接修饰,静态方法使用bean时报空指针异常错误...

發布時間:2025/3/15 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 autowired 静态方法使用_关于springboot工具类中@Autowired注入bean,用static直接修饰,静态方法使用bean时报空指针异常错误... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

錯誤場景:

springboot + mybatis

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

@Autowiredprivate staticMt4UsersMapper mt4UsersMapper;

@Autowiredprivate staticUserBankAccountsMapper userBankAccountsMapper;

@Autowiredprivate static UserProfilesMapper userProfilesMapper;

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

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

@Componentpublic classCreateReportTemFileUtil2 {

@AutowiredprivateMt4UsersMapper testmt4UsersMapper;private staticMt4UsersMapper mt4UsersMapper;

@AutowiredprivateUserBankAccountsMapper testuserBankAccountsMapper;private staticUserBankAccountsMapper userBankAccountsMapper;

@AutowiredprivateUserProfilesMapper testuserProfilesMapper;private staticUserProfilesMapper userProfilesMapper;

@PostConstructpublic voidinit(){

mt4UsersMapper= this.testmt4UsersMapper;

userBankAccountsMapper= this.testuserBankAccountsMapper;

userProfilesMapper= this.testuserProfilesMapper;

}

}

劃重點注解也很重要。

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

總結

以上是生活随笔為你收集整理的autowired 静态方法使用_关于springboot工具类中@Autowired注入bean,用static直接修饰,静态方法使用bean时报空指针异常错误...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。