@Autowired-service層注入對象為 null



當你看到這篇文章的時候,你@Autowired注入的對象可能是 null值,但是你不要沮喪,下面的代碼可能會幫到你.

在遵循 spring 管理的前提下,我們一定是不能 new 的,那下面我們就看一下代碼吧!

@Component // ------------------將工具類聲明為spring組件,這個必須不能忘      

public class Test {

    @Autowired
    private IMailService mailService;

    private static Test test;  // 靜態初使化當前類

    public void setMailService(IMailService mailService) {

        this.mailService = mailService;

    }

 

// 在方法上加上注解@PostConstruct,這樣方法就會在Bean初始化之后被Spring容器執行

//(注:Bean初始化包括,實例化Bean,並裝配Bean的屬性(依賴注入))。

    @PostConstruct 
    public void init() {
        test = this;
        test.mailService = this.mailService;

    }

 

//調用 mailService
test .mailService.sendFreemarker();

原文鏈接:https://blog.csdn.net/haoxiaoyong1014/article/details/79205676

 

 有問題可加微信聯系我一起學習探討 : 18237185359


免責聲明!

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



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