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

原因: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);
    }

 

posted on 2021-08-19 22:18  西八没天台  阅读(1363)  评论(0编辑  收藏  举报