项目场景:
今天在用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 基于接口的代理。
我是张同学,记录下工作中出现的问题。
不积跬步,无以至千里;不积小流,无以成江海。