@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