SpringBoot 加入AOP后无法注入的解决办法

本文介绍了解决SpringBoot应用中AOP无法正确注入Bean的问题。通过设置application.properties中的spring.aop.proxy-target-class=true来启用CGLIB代理,解决了NoSuchBeanDefinitionException和ClassCastException错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot 开启AOP后 出现无法注入的问题 真是坑的很啊

提示错误

org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type

或者

java.lang.ClassCastException: com.sun.proxy.$Proxy12 cannot be cast to cn.edu.nuc.SpringTest.service.impl.DemoServiceImpl

解决办法:

在application.properties中添加配置

#true为使用CGLIB代理,false为JDK代理,默认为false
spring.aop.proxy-target-class=true
引以为戒啊!!!!!!!
在Spring Boot应用中,如果你发现异步任务无法正常获取依赖注入的对象,通常是由于**@Async注解**所修饰的方法运行在一个新的线程中,而这个新线程并没有继承Spring容器上下文环境导致的。 ### 解决方案 #### 确保组件扫描和配置正确 首先确认你的类是否被`@ComponentScan`标注并且已经加入到Spring IOC 容器当中。例如: ```java @Component public class MyService { public void doSomething() { System.out.println("Doing something..."); } } ``` 然后,在需要使用异步的地方通过构造函数或字段注入该服务。 ```java @Service public class AsyncService { private final MyService myService; @Autowired public AsyncService(MyService myService) { this.myService = myService; } @Async // 标记为异步方法 public void asyncMethod() { myService.doSomething(); // 调用已注入的服务实例 } } ``` #### 配置@EnableAsync开启异步支持 别忘了启用Spring的异步功能,这一步非常重要! ```java @SpringBootApplication @EnableAsync // 开启异步功能 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 如果仍然有问题,请检查以下几点: 1. **代理模式问题**: 默认情况下Spring会创建JDK动态代理对象来进行AOP操作。但是当目标类实现了接口时,默认只会基于接口生成代理;因此若存在直接访问本类成员变量的情况,则可能出现空指针异常等问题。可以尝试切换成CGLIB代理形式: ```properties spring.aop.proxy-target-class=true ``` 2. **多线程间共享数据的问题**: 如果你在主线程内设置了某些静态变量或者ThreadLocal值,并希望它们能在子线程里继续有效的话,记得手动传递过去。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

love13135816

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值