一 首先在Spring的配置文件中开启注解扫描
<aop:aspectj-autoproxy proxy-target-class="true"/>
二 在要实现的AOP功能类上加上@Component @Aspect这两个注解
三 在功能上添加通知类型
@Before 前置通知
@AfterReturning 后置通知
@AfterThrowing 异常通知
@Around 环绕通知
@After 最终通知
四 切入点
切入点实例来源(点击打开链接)
方法限定表达式 execution(修饰符? 返回类型 方法名(参数) throws 异常类型?)
//所有public方法
execution(public * *(..))
//所有以set开头的方法
execution(* set*(..))
//com.xyz.service.AccountService中的所有方法
execution(* com.xyz.service.AccountService.*(..))
//com.xyz.service包下的所有类的所有方法
execution(* com.xyz.service.*.*(..))
//com.xyz.service包及其子包下的所有类的所有方法
execution(* com.xyz.service..*.*(..))
类型限定表达式
within(包名.类型)
//com.xyz.service下所有类的所有方法
within(com.xyz.service.*)
//com.xyz.service及其子包下所有类的所有方法
within(com.xyz.service..*)
五 示例
@Component
@Aspect
public class AspectComponent {
@Before(value = "execution(* com.test.controller.*.*(..))")
public void before(){
System.out.println("开始测试");
}
@AfterReturning(value = "within(com.test.controller.*)")
public void after(){
System.out.println("结束测试");
}
}
@Controller
public class TestAopController {
@RequestMapping("/testAop.do")
public void sayHi(){
System.out.println("hello world");
}
}