Spring AOP中的切入点“或”组合

时间:2017-02-04 14:56:52

标签: java spring spring-aop

我有一个类BigManPlay实现了一个接口Performance

@Component
public class BigManPlay implements Performance {
    @Override
    public void perform() {
        System.out.println("Performing 111!");
    }

    @Override
    public void perform2() {
        System.out.println("Performing 222!");
    }
}

然后,我希望perform()方法和perform2()接口中的每个方法(意味着Performance)都是建议目标。所以我写了以下方面类:

@Aspect
public class Audience {

    @Pointcut("execution(* Chapter_4_2_1.concert.Performance.perform(..)) or within(Chapter_4_2_1.concert.Performance+)")
    public void performance() {}

    @Before("performance()")
    public void silenceCellPhones() {
        System.out.println("Silencing cell phones");
    }
    @Before("performance()")
    public void takeSeats() {
        System.out.println("Taking seats");
    }
    @AfterReturning("performance()")
    public void applause() {
        System.out.println("CLAP CLAP CLAP!!!");
    }
}

然后是一个连接bean的java配置类:

@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = {"Chapter_4_2_1.concert"})
public class ConcertConfig {
    @Bean
    public Audience audience() {
        return new Audience();
    }
}

然后是UT类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=ConcertConfig.class)
public class PerformanceTest {

    @Autowired
    Performance bigManPlay;

    @Rule
    public final SystemOutRule log = new SystemOutRule().enableLog();

    @Test
    public void testWithPerformance() {
        log.clearLog();
        bigManPlay.perform();
        assertEquals("Silencing cell phones" + System.lineSeparator()
                + "Taking seats" + System.lineSeparator()
                + "Performing 111!" + System.lineSeparator()
                + "CLAP CLAP CLAP!!!" + System.lineSeparator(), log.getLog());
    }


    @Test
    public void testWithPerformance2() {
        log.clearLog();
        bigManPlay.perform2();
        assertEquals("Silencing cell phones" + System.lineSeparator()
            + "Taking seats" + System.lineSeparator()
            + "Performing 222!" + System.lineSeparator()
            + "CLAP CLAP CLAP!!!" + System.lineSeparator(), log.getLog());
    }
}

UT失败了。 testWithPerformance2()仅输出

Performing 222!

within(Chapter_4_2_1.concert.Performance+)没有生效,为什么?

1 个答案:

答案 0 :(得分:0)

The syntax for pointcut composition for "or" is ||

  

Pointcut0 || Pointcut1Pointcut0选出的每个加入点   或Pointcut1

这看起来像

@Pointcut("execution(* Chapter_4_2_1.concert.Performance.perform(..)) || within(Chapter_4_2_1.concert.Performance+)")

基本上,解析器找到第一个切入点表达式execution,并停止解析,因为剩下的表达式中没有其他合成标记。你可以写任何东西

@Pointcut("execution(* Chapter_4_2_1.concert.Performance.perform(..)) blabla")

并且它无法解析。它会为execution创建一个有效的切入点。