2017-02-04 59 views
0

我有一個類BigManPlay實現一個接口Performance切入點「或」在Spring AOP組合物

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

然後一個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+)沒有生效,爲什麼呢?

回答

0

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

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