SpringBoot无法注入bean的问题:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

在SpringBoot项目中使用AspectJ时遇到日志bean注入失败的问题,错误提示bean不存在。解决方案是在启动类添加@EnableAspectJAutoProxy(exposeProxy = true),这与proxy-target-class属性有关,它决定了代理类型。通过记录和解决此类问题,有助于积累开发经验。

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

项目场景:

今天在用SpringBoot写项目的时候,用AspectJ类的时候,发现日志的bean注入不进去,直接报错类似这样的 内联代码片

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'RoomDAO': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private es.rooms.db.spring.dao.PlayerDAO es.rooms.db.spring.dao.RoomDAO.playerDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [es.rooms.db.spring.dao.PlayerDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}




原因分析:

就很明显,提示bean注入不进去,看意思是在用@Autowired注解的时候,该bean不存在,注入失败,那么就去找解决问题的方案


解决方案:

是在applicationContext.xml里面,加上**aop:aspectj-autoproxy/**配置,改为如下就好了。

 <aop:aspectj-autoproxy proxy-target-class="true" expose-proxy="true"/>

在SpringBoot的话,就在启动类,加上@EnableAspectJAutoProxy(exposeProxy = true)就好了。

@EnableAspectJAutoProxy(exposeProxy = true)
public class Application {

}

原因:proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。如果proxy-target-class 属性值被设置为true,那么基于类的代理将起作用(这时需要cglib库)。如果proxy-target-class属值被设置为false或者这个属性被省略,那么标准的JDK 基于接口的代理。

我是张同学,记录下工作中出现的问题。
不积跬步,无以至千里;不积小流,无以成江海。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值