【问题标题】:How to advice JUnit methods with Spring AOP如何使用 Spring AOP 为 JUnit 方法提供建议
【发布时间】:2014-03-31 19:46:13
【问题描述】:

我有一个扩展 AbstractTransactionalJUnit4SpringContextTests 的类。我想为每个子类建议 @Before 方法。 但是,在我的 Aspect 类中,我无法注入任何这些实例。我查看了在应用程序上下文中创建的 bean,但看不到任何测试 bean。那么我怎样才能得到它们或者 spring 是如何创建这些 bean 的呢?

@ContextConfiguration(locations = {"/test-context.xml"})
    public abstract class Ab extends AbstractTransactionalJUnit4SpringContextTests {
}

public class MyTests extends Ab {
    @Before //I want to advice this
    public void before() {}
}

@Aspect
public class BeforeTestsAspect {
    @Autowired //it won't find any bean of type Ab
    private Ab ab;
}

【问题讨论】:

  • Spring 不会创建这些 bean,JUnit 会。您应该告诉我们您实际想要达到的目标。可能还有其他解决方案。
  • 我基本上想实现这个问题中描述的内容。 stackoverflow.com/questions/17505952/… 但该解决方案是不可接受的,因为那样会为每个类运行脚本。

标签: spring junit spring-aop


【解决方案1】:

你应该看看使用 aspectj 而不是 spring aop 有一个很好的例子来说明如何设置它here

aspectj 允许您切入应用程序或测试中的任何类,而不仅仅是那些由 s​​pring 创建的类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    相关资源
    最近更新 更多