java - @DeclareParents 未能引入新方法

标签 java spring aop

大家好,我是Spring的初学者,在使用@DeclareParents时遇到了一些问题。我按照Spring In Action中的说明进行操作,但我没有意识到其中的介绍。

这是我的代码。 我首先定义接口(interface)性能

public interface Performance {
    void perform();
}

然后实现接口(interface)。

@Component
public class OnePerformance implements Performance {
    @Autowired
    public OnePerformance(){
    }

    public void perform() {
        System.out.println("The Band is performing....");
    }

}

我想将方法​​void PerformEncore()引入到Performance中。 所以我定义了接口(interface),

public interface Encoreable {
    void performEncore();
}

实现它,

@Aspect
public class DefaultEncoreable implements Encoreable{
    public void performEncore() {
        System.out.println("performEncore");
    }
}

并介绍一下,

@Aspect
@Component
public class EncoreableIntroduction {            
    @DeclareParents(value="Performance+",
        , defaultImpl=DefaultEncoreable.class)
     public static Encoreable encoreable;
}

我使用自动配置,

@Configuration
@EnableAspectJAutoProxy
@ComponentScan
public class ConcertConfig {
}

但是,在测试时,我未能引入方法 void PerformEncore()。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= ConcertConfig.class)
public class OnePerformanceTest {
    @Autowired
    private Performance performance;

    @Test
    public void perform() throws Exception {
        performance.perform();
}}

Junit4 Test Class

我还启用了 AspectJ 支持插件。 My IntelliJ IDEA PLUGIN Settings

我仔细阅读了这本书和几篇博客,但仍然找不到原因。那么造成这个问题的原因可能是什么呢?提前致谢。

最佳答案

感谢 M. Deinum、NewUser 和 Wim Deblauwe。在他们的帮助下,我终于解决了问题。之前的 JUnit4 类不正确。

解决这个问题的正确方法是将Performance转换为Encoreable,然后调用performEncore()方法。

代码如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= ConcertConfig.class)
public class OnePerformanceTest {
    @Autowired
    private Performance performance;

    @Test
    public void perform() throws Exception {
        Encoreable encoreable = (Encoreable)(performance);
        encoreable.performEncore();
    }
}

screen capture of the final result

关于java - @DeclareParents 未能引入新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41756848/

相关文章:

java - cucumber testng 运行程序失败

Java Spring 安全 OAuth2 : Accept client credentials via POST

java - IDEA 无法在插件依赖项中找到 AspectJ 编译器 .jar

java - Spring自定义错误页面返回没有显式映射的/错误

c# - DBC(契约式设计)和AOP(面向切面编程)

spring - Spring AOP 中抛出异常

java - 如何在selenium中关闭IEDriverServer.exe?

java - 如何从 Java 中的特定键值开始迭代 HashMap?

java - Android - startActivityForResult 用于获取文件路径

java - 如何告诉 Mockito 使用帮助类的真实(未模拟)版本?