首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring(Java):方面不会在非线性类层次结构中触发

Spring(Java):方面不会在非线性类层次结构中触发
EN

Stack Overflow用户
提问于 2015-02-04 09:20:00
回答 1查看 289关注 0票数 6

如果类层次结构不是线性的,则在基本接口上定义方面时不会触发方面。

最有趣的是:当向实现的父类添加委托实现(请参阅最后一个代码块)时,测试变为Green (方面按预期触发)。

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

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

测试:

代码语言:javascript
复制
 @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);
}

方面:

代码语言:javascript
复制
@Aspect
@Component
public static class MyAspect {

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

接口:

代码语言:javascript
复制
public static interface TheInterface {
    void doSomething();
}

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

抽象实现(模板模式):

代码语言:javascript
复制
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:

代码语言:javascript
复制
@Component
public static class TemplateImplementation extends SpecializedTemplate {
    @Override
    void doOneStep() {
        implementationCalled = true;
    }
}

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

代码语言:javascript
复制
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyConfig.class)
public class AopTest {
    @Configuration
    @EnableAspectJAutoProxy
    @ComponentScan(basePackageClasses = AopTest.class)
    public static class MyConfig {
    }
    ...

丑陋的解决方案:将此片段添加到SpecializedTemplate中

代码语言:javascript
复制
    @Override
    public void doSomething() {
        super.doSomething();
    }

那么,为什么有必要解决这个问题呢?

EN

回答 1

Stack Overflow用户

发布于 2015-02-07 09:32:56

Thomas已经解释了字节码和JVM的内容,所以我将只为您的问题提供一个解决方案,也请参阅我的answer中的一个非常类似的问题。

代码语言:javascript
复制
@Aspect
public static class MyAspect {
    @Before("execution(* *..TheInterface+.doSomething()) && target(specializedInterface)")
    public void applyAspect(SpecializedInterface specializedInterface) {
        aspectCalled = true;
    }
}

也就是说,切入点的目标是实际定义方法的基本接口,然后将目标限制在您选择的专门的子接口上。这应该会让你的测试变绿。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28317650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档