首页 > 编程语言 > 详细

SpringBoot中非Controller类调用service方法出现null空指针

时间:2021-08-20 09:17:21      阅读:22      评论:0      收藏:0      [点我收藏+]

原因:service无法导入到非controller层中去。

 

解决方法:注入bean

@Component  //重点
public class TestServerse{
    @Autowired
    //正常引用目标service  
    private OtherService otherService ;
    //将自己作为静态变量引入,使SpringBoot初始化之前就被创建
    public static TestServerse testServerse; //public极为重要
     /**
     * 重新构造一个方法
     * 通过 @PreDestroy 或 @PostContruct 实现初始化和销毁bean之前进行的操作
     * @PostContruct 这个注解就是在springboot启动前就加载
     */
    @PostConstruct 
    public void init() {  
        testServerse = this;  
        testServerse.otherService = this.otherService ;        
        // 初使化时将已静态化的otherService实例化
    }  
    //测试调用
    public void test(){
        //调用时需要用testServerse.otherService的方式使用目标otherservice中的addXX方法
        testServerse.otherService.addXX(xx);
    }

 

SpringBoot中非Controller类调用service方法出现null空指针

原文:https://www.cnblogs.com/stupid-chan/p/15164299.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!