gpt4 book ai didi

java - Spring (Java): Aspect is not triggered in non linear class hierarchy

转载 作者:搜寻专家 更新时间:2023-11-01 00:56:10 25 4
gpt4 key购买 nike

当类层次结构不是线性时,在基接口(interface)上定义方面不会触发。

最有趣的是:当向实现的父类添加委托(delegate)实现(见最后一个代码块)时,测试变为绿色(Aspect 按预期触发)。

问题:为什么它不像示例中描述的那样工作,为什么它与委托(delegate)实现一起工作?

示例(抱歉,没有找到更短的示例):

测试:

 @Autowired
private TheInterface underTest;
private static boolean aspectCalled;
private static boolean implementationCalled;

@Test
public void aspectTest() throws Exception {
aspectCalled = false;
implementationCalled = false;

underTest.doSomething();

assertTrue("Implementation not called!", implementationCalled);
assertTrue("Aspect not called!", aspectCalled);
}

看点:

@Aspect
@Component
public static class MyAspect {

@Before("execution(* *..SpecializedInterface+.doSomething())")
public void applyAspect() {
aspectCalled = true;
}
}

接口(interface):

public static interface TheInterface {
void doSomething();
}

public static interface SpecializedInterface extends TheInterface {
// inherits doSomething
// defines some other methods
}

抽象实现(模板模式):

public static abstract class BaseTemplate implements TheInterface {
abstract void doOneStep();

@Override
public void doSomething() {
// do some stuff and
doOneStep();
}
}

public static abstract class SpecializedTemplate extends BaseTemplate implements SpecializedInterface {
// some other methods
}

实现bean:

@Component
public static class TemplateImplementation extends SpecializedTemplate {
@Override
void doOneStep() {
implementationCalled = true;
}
}

(如果您有兴趣:测试设置:)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyConfig.class)
public class AopTest {
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackageClasses = AopTest.class)
public static class MyConfig {
}
...

丑陋的解决方法:将此代码段添加到 SpecializedTemplate

    @Override
public void doSomething() {
super.doSomething();
}

那么,为什么需要这种解决方法?

最佳答案

Thomas Stets 已经解释了字节码和 JVM 的东西,所以我将只提供一个解决你的问题的方法,另请参阅我的 answer一个非常相似的问题。

@Aspect
public static class MyAspect {
@Before("execution(* *..TheInterface+.doSomething()) && target(specializedInterface)")
public void applyAspect(SpecializedInterface specializedInterface) {
aspectCalled = true;
}
}

即您的切入点以实际定义方法的基本接口(interface)为目标,然后将目标限制为您选择的专用子接口(interface)。这应该使您的测试通过。

关于java - Spring (Java): Aspect is not triggered in non linear class hierarchy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28317650/

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