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);
    }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM