當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot @Async加在实现接口类的非接口方法上获取Bean异常
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot @Async加在实现接口类的非接口方法上获取Bean异常
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、場景復現
報錯日志
*************************** APPLICATION FAILED TO START ***************************Description:A component required a bean of type 'com.mk.service.TestService' that could not be found.Action:Consider defining a bean of type 'com.mk.service.TestService' in your configuration @Service public class TestService implements ITestService{@Asyncpublic Future<String> doActionAsync(){return new AsyncResult(doAction());}@Overridepublic String doAction() {return "done";} }public interface ITestService {String doAction(); }@Component public class Runner implements ApplicationContextAware {@EventListener(ApplicationReadyEvent.class)public void run(){TestService testService = applicationContext.getBean(TestService.class);testService.doActionAsync();}private ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext =applicationContext;} }@EnableAsync @Configuration @SpringBootApplication public class ServiceApplication {public static void main(String[] args) {SpringApplication.run(ServiceApplication.class, args);}}二、分析原因
(1)doActionAsync加上接口方法,執行一樣報錯
@Service public class TestService implements ITestService{@Override@Asyncpublic Future<String> doActionAsync(){return new AsyncResult(doAction());}@Overridepublic String doAction() {return "done";} }(2)使用ITestService調用就不報錯
@Component public class Runner implements ApplicationContextAware {@EventListener(ApplicationReadyEvent.class)public void run(){ITestService testService = applicationContext.getBean(ITestService.class);testService.doActionAsync();}private ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext =applicationContext;} }(3)Springboot 代理類型
Springboot 默認代理類型為jdk proxy
bean有實現接口使用jdk proxy代理,沒有實現接口則使用cglib代理
?
三、解決方案
(1)將方法抽象到接口
(2)強制使用cglib代理
@EnableAsync(proxyTargetClass = true) @Configuration @SpringBootApplication public class ServiceApplication {public static void main(String[] args) {SpringApplication.run(ServiceApplication.class, args);}}?
總結
以上是生活随笔為你收集整理的SpringBoot @Async加在实现接口类的非接口方法上获取Bean异常的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 手写福字制作方法 如何制作手写福字
- 下一篇: SpringCloud Greenwic