簡體   English   中英

Spring AOP中的切入點“或”組合

[英]Pointcut “or” composition in Spring AOP

我有一個BigManPlay類, 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!");
    }
}

然后,我希望Performance接口中的perform()方法和每個方法(意味着perform2() )都是建議目標。 因此,我編寫了以下方面類:

@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!!!");
    }
}

然后是一個Java config類來連接bean:

@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+)無效,為什么?

“或”的切入點合成的語法為||

Pointcut0 || Pointcut1 Pointcut0 || Pointcut1 Pointcut0Pointcut1拾取的每個連接點

看起來像

@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創建有效的切入點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM