3.9 @Pointcut的表達式-within


戴着假發的程序員出品  抖音ID:戴着假發的程序員  歡迎關注

[查看視頻教程]

限制匹配某些類型中的連接點(使用 Spring AOP 時執行在匹配類型中聲明的方法)。

spring官方給出的案例:

service包中的任何連接點(僅在 Spring AOP 中執行方法):

within(com.st.dk.service.*)

service包中的任何連接點(僅在 Spring AOP 中執行方法)或其中一個 sub-packages:

within(com.st.dk.service..*)

我們來看看案例:

我們調整我們的項目結構,在service包下定義BookService和AuthorService類。 在service.sub包下定義TopicService:

內容如下:

/**
 * @author 戴着假發的程序員
 * 
 * @description
 */
@Component
public class BookService{
    public void saveBook(String title){
        System.out.println("保存圖書:"+title);
    }
}
/**
 * @author 戴着假發的程序員
 * 
 * @description
 */
@Component
public class AuthorServicde {
    public  void saveAuthor(String name){
        System.out.println("保存作者:"+name);
    }
}
/**
 * @author 戴着假發的程序員
 * 
 * @description
 */
@Component
public class TopicService {
    public void saveTopic(String title){
        System.out.println("保存話題:"+title);
    }
}

Aspect類配置如下:

/**
 * @author 戴着假發的程序員
 * 
 * @description
 */
@Component //將當前bean交給spring管理
@Aspect //定義為一個AspectBean
public class DkAspect {
    @Pointcut("within(com.st.dk.demo7.service.*)")
    private void pointCut1(){}
    //定義一個前置通知
    @Before("pointCut1()")
    private static void befor(){
        System.out.println("---前置通知---");
    }
}

測試:

@Test
public void testAopPointCutWithin(){
    ApplicationContext ac =
            new AnnotationConfigApplicationContext(Appconfig.class);
    BookService bean = ac.getBean(BookService.class);
    bean.saveBook("論一個假發程序員的修養");
    AuthorServicde bean1 = ac.getBean(AuthorServicde.class);
    bean1.saveAuthor("戴着假發的程序員");
    TopicService bean2 = ac.getBean(TopicService.class);
    bean2.saveTopic("論一個程序員的修養");
}

結果:

我們會發現service包下的直接類會被增強,但是service.sub中的TopicService並未增強。

我們可以通過 within(com.st.dk.service..*) 配置讓spring對象service包已經子孫包中的所有類的所有方法進行增強。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM