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