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包已经子孙包中的所有类的所有方法进行增强。

posted @ 2020-10-17 17:20  戴着假发的程序员0-1  阅读(2022)  评论(0编辑  收藏  举报