gpt4 book ai didi

java - Spring AOP 代理没有按预期工作

转载 作者:搜寻专家 更新时间:2023-10-31 20:27:38 24 4
gpt4 key购买 nike

实际上我对 spring 代理的行为感到困惑。我想我知道 j2ee、cglib 和 aspectj 的代理机制之间的主要区别。我在我的配置类中启用了 aspectj 自动代理,并且 aspectj 包含在类路径中。

我的配置

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ApplicationConfiguration {
...
}

AspectJ 依赖

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.5</version>
</dependency>

通过使用这个简单的设置,我假设 bean 注入(inject)按预期工作。但相反,我的应用程序导致 IllegalArgumentException 出现消息,如“无法将 [...] 字段 [...] 设置为 com.sun.proxy.$Proxy30”。这意味着 spring 为我的服务使用 j2ee 代理,即使启用了 aspectj 代理也是如此。

最后我发现是我服务上的接口(interface)导致了这种行为。似乎spring决定在我的服务实现任何接口(interface)时使用j2ee代理。如果我删除它们,它就会起作用。

失败:

@Service
@Validated
public class MyService implements Interface1, Interface2 {

@override
public void methodFromInterface1() {
}

@override
public void methodFromInterface2() {
}

public void serviceMethod() {
}
}

确定:

@Service
@Validated
public class MyService {

public void methodFromInterface1() {
}

public void methodFromInterface2() {
}

public void serviceMethod() {
}
}

到目前为止,我已经了解 j2ee 代理需要接口(interface)。但这对我来说是新的,cglib/aspectj 代理不适用于实现接口(interface)的 bean。

有没有办法...

...强制 spring 不使用 j2ee 代理?

...强制 spring 使用 cglib/aspectj 代理(即使对于具有接口(interface)的类)?

这是 spring 的错误还是期望的行为?

编辑:示例已更新,@Transational 替换为 @Validated

Edit2:解决方案: @ValidatedMethodValidationPostProcessor 影响。因此必须为此 bean 将属性 proxyTargetClass 设置为 true

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
final MethodValidationPostProcessor methodValidationPostProcessor;
methodValidationPostProcessor = new MethodValidationPostProcessor();
methodValidationPostProcessor.setProxyTargetClass(true);
return methodValidationPostProcessor;
}

最佳答案

@EnableAspectJAutoProxy注解适用于 @Aspect 注解,不适用于 @Transactional 注解。为此,您需要 @EnableTransactionManagement @Configuration 类上的注释,具有 proxyTargetClass = true 属性值。

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableTransactionManagement(proxyTargetClass = true)
public class ApplicationConfiguration {
...
}

关于java - Spring AOP 代理没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29085974/

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