gpt4 book ai didi

spring - 将 @EnableCaching 与自定义 AOP 建议一起使用时,代理类型不匹配(JDK 与 CGLIB)

转载 作者:行者123 更新时间:2023-12-02 11:41:41 25 4
gpt4 key购买 nike

我一直在尝试让 Spring 的声明式缓存与一些自定义 AOP 建议一起在应用程序中工作,但遇到了代理类型不匹配的问题。

给定以下 Spring Boot 应用程序主类:

@SpringBootApplication
@EnableCaching
public class Application {

@Bean
public DefaultAdvisorAutoProxyCreator proxyCreator() {
return new DefaultAdvisorAutoProxyCreator();
}

@Bean
public NameMatchMethodPointcutAdvisor pointcutAdvisor() {
NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor();
advisor.setClassFilter(new RootClassFilter(Service.class));
advisor.addMethodName("*");
advisor.setAdvice(new EnsureNonNegativeAdvice());
return advisor;
}

public static class EnsureNonNegativeAdvice implements MethodBeforeAdvice {

@Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
if ((int) args[0] < 0) {
throw new IllegalArgumentException();
}
}
}
}

和服务:

@Component
public class Service {

@Cacheable(cacheNames = "int-strings")
public String getString(int i) {
return String.valueOf(i);
}
}

我希望通过以下测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class)
public class ApplicationIT {

@Autowired
private Service service;

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void getStringWithNegativeThrowsException() {
thrown.expect(IllegalArgumentException.class);

service.getString(-1);
}
}

(此代码在 https://github.com/hdpe/spring-cache-and-aop-issue 上的可运​​行项目中全部可用)。

但是,运行此测试会给出:

org.springframework.beans.factory.UnsatisfiedDependencyException:
...<snip>...
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'service' is expected to be of type 'me.hdpe.spring.cacheandaop.Service' but was actually of type 'com.sun.proxy.$Proxy61'
at org.springframework.beans.factory.support.DefaultListableBeanFactory.checkBeanNotOfRequiredType(DefaultListableBeanFactory.java:1520)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1498)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1099)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1060)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:578)
...

这是为什么呢?嗯,我认为...

  • @EnableCaching触发 InfrastructureAdvisorAutoProxyCreator 的创建,它将很乐意通过Service附近的代理应用缓存建议。
  • Service不实现任何接口(interface),CGLIB 用于创建其代理
  • 我的DefaultAdvisorAutoProxyCreator然后运行以围绕服务方法应用我的自定义建议(似乎又是缓存建议)
  • 由于该服务现在实际上是一个 CGLIB 代理,并且已实现 SpringProxyAdvised Spring接口(interface),这次Spring创建了一个JDK动态代理
  • 动态代理不再是Service ,因此 Autowiring 到测试类中失败。

因此,为了解决问题(或者至少隐藏这个问题),我可以强制我的代理创建者生成 CGLIB 代理:

public DefaultAdvisorAutoProxyCreator proxyCreator() {
DefaultAdvisorAutoProxyCreator proxyCreator = new DefaultAdvisorAutoProxyCreator();
proxyCreator.setProxyTargetClass(true);
return proxyCreator;
}

然后我的测试通过了,同样我可以测试声明性缓存是否也可以运行。

所以我的问题:

这是解决此问题的最佳方法吗?让两个自动代理创建器适用于给定的 bean 是合法的还是个好主意?如果不是,那么让 Spring 的隐式自动代理创建器与自定义建议很好地配合的最佳方法是什么?我怀疑“嵌套”代理是个好主意,但无法弄清楚如何覆盖 @Enable*的隐式自动代理创建者。

最佳答案

我花费了大量的时间来研究这个问题并取得了一些进展。

经过更多思考,我认为根本问题并不是 Spring 选择了错误类型的代理来包装已经代理的 bean。 Spring 一开始就试图对一个 bean 进行双重代理!

TL;DR - 使用 @AspectJ 而不是 DefaultAdvisorAutoProxyCreator

我遇到的问题似乎是 SPR-13990 的表现(DefaultAdvisorAutoProxyCreator doesn't get the target class of existing proxy - 因无法修复而关闭)。讨论中稍后的评论与我的用例特别相关。来自维护者:

Spring's AutoProxyCreators actually always create a new proxy...

SPR-6083(DefaultAdvisorAutoProxyCreator doesn't work with tx:annotation-driven on Cglib classes - 也无法修复)也很有启发性;维护者说:

We do explicitly avoid double proxying, but only when using implicit proxies such as through <tx:annotation-driven> or <aop:config>. I'm afraid that an explicit DefaultAdvisorAutoProxyCreator definition won't participate in that process...

这些建议似乎是:

  1. 注册基础设施(在本例中为缓存)Advisor与你的DefaultAdvisorAutoProxyCreator你自己;或到
  2. 切换到“<aop:config>样式”配置。

注册Advisor你自己

通过删除 @EnableCaching并定义它包含我自己的bean, InfrastructureAdvisorAutoProxyCreator不会被注册,我可以继续使用我自己的自动代理创建器,我的 @Cacheable方法也会发挥作用。我的配置如下所示:

@SpringBootApplication
public class Application {

@Bean
public DefaultAdvisorAutoProxyCreator proxyCreator() {
return new DefaultAdvisorAutoProxyCreator();
}

@Bean
public CacheOperationSource cacheOperationSource() {
return new AnnotationCacheOperationSource();
}

@Bean
public CacheInterceptor cacheInterceptor() {
CacheInterceptor interceptor = new CacheInterceptor();
interceptor.setCacheOperationSources(cacheOperationSource());
return interceptor;
}

@Bean
public BeanFactoryCacheOperationSourceAdvisor cacheOperationSourceAdvisor() {
BeanFactoryCacheOperationSourceAdvisor advisor = new BeanFactoryCacheOperationSourceAdvisor();
advisor.setAdvice(cacheInterceptor());
advisor.setCacheOperationSource(cacheOperationSource());
return advisor;
}

@Bean
public NameMatchMethodPointcutAdvisor pointcutAdvisor() {
...

现在这非常可怕 - 我不得不毫无意义地重新定义许多核心 Spring 配置,这样我就可以将 AutoProxyRegistrar关闭,我失去了使用 CachingConfigurer 的能力以及可能还有各种其他东西。

@AspectJ

因此,当我发现 JavaConfig 中的“<aop:config> 样式”意味着 @AspectJ 注释时,第二种方法就是可行的方法。请注意,这里的 @AspectJ 并不意味着您正在使用 AspectJ 编译器/编织器!它仍然只是 Spring AOP 从 @AspectJ 注释创建 JDK 或 CGLIB 代理。

使用 @AspectJ 风格的配置,整个配置可以浓缩为:

@SpringBootApplication
@EnableCaching
@EnableAspectJAutoProxy
public class Application {

@Aspect
@Component
public static class EnsureNonNegativeAspect {

@Before("execution(* me.hdpe.spring.cacheandaop.Service.*(..)) && args(i)")
public void ensureNonNegative(int i) {
if (i < 0) {
throw new IllegalArgumentException();
}
}
}
}

令人难以置信的是,这有效,因为 @EnableAspectJAutoProxy 提升任何现有的InfrastructureAdvisorAutoProxyCreator到 @AspectJ 自动代理创建者,导致只有一个代理应用我的自定义和缓存建议。

总结一下

我认为如果您想将自定义 Spring AOP 建议与 @EnableCaching 创建的隐式建议一起使用, @EnableTransactionManagement等等,使用 @AspectJ 而不是 DefaultAdvisorAutoProxyCreator 可能会更好。这似乎是 Spring 希望你走下去的方向,他们也暗示了 in the docs :

The previous chapter described the Spring's support for AOP using @AspectJ and schema-based aspect definitions. In this chapter we discuss the lower-level Spring AOP APIs and the AOP support typically used in Spring 1.2 applications. For new applications, we recommend the use of the Spring 2.0 and later AOP support described in the previous chapter...

...但是 DefaultAdvisorAutoProxyCreator似乎无处不在,我认为它是“较低级别”而不是“Spring 1.2”。

关于spring - 将 @EnableCaching 与自定义 AOP 建议一起使用时,代理类型不匹配(JDK 与 CGLIB),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47056617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com