@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

posted on 2019-12-04 14:07  不听话的M老大  阅读(7511)  评论(0编辑  收藏  举报

导航