戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注
@Pointcut的表达式-@annotation
spring应用手册(第三部分)
限制连接点的匹配,其中连接点的主题(在 Spring AOP 中执行的方法)具有给定的 annotation。
官方案例:
任何连接点(仅在 Spring AOP 中执行方法),其中执行方法具有@Transactional annotation:
@annotation(org.springframework.transaction.annotation.Transactional)
官方的案例已经说的很清楚了,就是@annotation是匹配拥有指定注解的方法的。这里要注意,@annotation只匹配实现类中的有注解的方法,不会匹配接口中的注解方法。
看案例:
我们准备接口:
/**
* @author 戴着假发的程序员
*
* @description
*/
public interface IBookService {
//@DkAnnotation// 这里的注解是不会被匹配的
public void saveBook(String title);
}
实现类:
/**
* @author 戴着假发的程序员
*
* @description
*/
@Component
public class BookService implements IBookService{
@Override
@DkAnnotation //这里的注解会被匹配
public void saveBook(String title){
System.out.println("保存图书:"+title);
}
public void saveBook(String title,int count){
System.out.println("保存"+title+","+count+"次");
}
}
修改Aspect类:
/**
* @author 戴着假发的程序员
*
* @description
*/
@Component //将当前bean交给spring管理
@Aspect //定义为一个AspectBean
public class DkAspect {
//使用@annotation配置匹配所有还有指定注解的方法
@Pointcut("@annotation(com.st.dk.demo7.annotations.DkAnnotation)")
private void pointCut1(){}
//定义一个前置通知
@Before("pointCut1()")
private static void befor(){
System.out.println("---前置通知---");
}
}
测试:
@Test
public void testAopPoint_annotation(){
ApplicationContext ac =
new AnnotationConfigApplicationContext(Appconfig.class);
IBookService bean = ac.getBean(IBookService.class);
bean.saveBook("程序员的修养");
}
结果: