大家好,我是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();
}}
我仔细阅读了这本书和几篇博客,但仍然找不到原因。那么造成这个问题的原因可能是什么呢?提前致谢。
最佳答案
感谢 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();
}
}
关于java - @DeclareParents 未能引入新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41756848/