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