引入spring-boot-starter-data-jpa后CGLIB增强失效问题排查
问题排查记录
初始现象
引入spring-boot-starter-data-jpa前,@Cacheable和@CachePut注解功能正常,相关Bean代码如下:
@Service public class BasicAuthRestTemplate { @Cacheable(value = "restTemplate", key = "#email") public RestTemplate getRestTemplate(String email) { return null; } @CachePut(value = "restTemplate", key = "#email") public RestTemplate getRestTemplate(String email, String password) { return new RestTemplateBuilder().basicAuthentication(email, password).build(); } }
启动日志分析
系统选择CglibAutoProxyConfiguration时,CGLIB增强失效:
the bean can not be enhanced by CGLIB: AopAutoConfiguration.AspectJAutoProxyingConfiguration matched: - @ConditionalOnClass found required class 'org.aspectj.weaver.Advice' (OnClassCondition) AopAutoConfiguration.AspectJAutoProxyingConfiguration.CglibAutoProxyConfiguration matched: - @ConditionalOnProperty (spring.aop.proxy-target-class=true) matched (OnPropertyCondition) AopAutoConfiguration.ClassProxyingConfiguration: Did not match: - @ConditionalOnMissingClass found unwanted class 'org.aspectj.weaver.Advice' (OnClassCondition) ================================================================================================ the bean can be enhaced by CGLIB : AopAutoConfiguration.ClassProxyingConfiguration matched: - @ConditionalOnMissingClass did not find unwanted class 'org.aspectj.weaver.Advice' (OnClassCondition) - @ConditionalOnProperty (spring.aop.proxy-target-class=true) matched (OnPropertyCondition) AopAutoConfiguration.AspectJAutoProxyingConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.aspectj.weaver.Advice' (OnClassCondition)
初步排查结果
排除spring-boot-starter-data-jpa依赖中的aspectjweaver后,注解功能恢复正常,确认该依赖是问题诱因:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <exclusions> <exclusion> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> </exclusion> </exclusions> </dependency>
后续排查更新
2023/05/31
未引入aspectjweaver时,Bean初始化完成后会调用postProcessAfterInitialization,可通过spring framework.cache.interceptor.CacheInterceptor对Bean完成代理。
2023/06/01
进一步排查发现并非aspectjweaver依赖本身的问题(此前同项目添加JPA依赖功能正常),实际原因是引入该依赖时,org.springframework.cache.config.internalCacheAdvisor无法加入候选增强器列表,根源是this.beanFactory.isCurrentlyInCreation(name)返回true。
2023/06/02
找到Spring官方同类问题记录,临时解决方案为使用@Lazy注解注入Bean:
@Lazy @Autowired private BasicAuthRestTemplate basicAuthRestTemplate;
但该问题在框架层面仍有优化空间。
内容的提问来源于stack exchange,提问作者socia1ca3t
相关产品推荐
相关产品推荐

