首页 > 技术文章 > spring aop

gqymy 2018-08-29 16:00 原文

spring-AOP
    * 起始对象
    * 目标对象
    * 切面
    * 代理对象
    * 切入点 (代理或切面引入的条件,目标对象的一个方法。)
    * 连接点 (切面中执行的一个方法)
    * 通知 (连接点中具体执行的操作)
        * 语法形式:代码段,方法,对象。
        * 种类:
            * 前置通知
            * 后置通知
            * 异常通知
            * 最终通知
            * 环绕通知
 
* 机制:只需要向spring要所需的目标对象即可。
        spring会根据配置情况,如果此次执行目标对象时需要经过切面,则spring会自动提供一个代理。
        我们以为拿到的是目标对象,其实拿到的是代理对象。
 
下面是本人写的demo
 
@Aspect
@Component
public class TestAop {
 
/**
* JoinPoint里包含了类名、被切面的方法名,参数等属性,可供读取使用。@Around参数必须为ProceedingJoinPoint,
* pjp.proceed相应于执行被切面的方法。@AfterReturning方法里,可以加returning = “XXX”,
* XXX即为在controller里方法的返回值,本例中的返回值是“first controller”。
* @AfterThrowing方法里,可以加throwing = "XXX",供读取异常信息
*/
 
/**
* execution函数用于匹配方法执行的连接点,语法为:
* execution(方法修饰符(可选) 返回类型 方法名 参数 异常模式(可选))
*/
@Pointcut("execution(* com.wjc.ccf.web.*.*(..))")
public void dataSourcePointCut(){
 
}
 
@Before("dataSourcePointCut()")
public void doBefore(JoinPoint joinPoint){
System.out.println("before 标识一个前置增强方法,相当于BeforeAdvice的功能");
}
 
@After("dataSourcePointCut()")
public void doAfter(JoinPoint joinPoint){
System.out.println("after final增强,不管是抛出异常或者正常退出都会执行");
}
 
@AfterReturning(pointcut = "dataSourcePointCut()")
public void doAfterReturning(JoinPoint joinPoint){
System.out.println("afterReturn 后置增强,相当于AfterReturningAdvice,方法退出时执行");
}
 
@AfterThrowing(pointcut = "dataSourcePointCut()", throwing = "throwable")
public void doAfterThrowing(JoinPoint joinPoint, Throwable throwable){
System.out.println("afterThrow 异常抛出增强,相当于ThrowsAdvice");
}
 
@Around("dataSourcePointCut()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("around 环绕增强,相当于MethodInterceptor");
return pjp.proceed();
}
 
这是我的项目入口,可以自己随便写一个进行测试,但是记得修改切入点的路径
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(){
 
System.out.println("===========");
Subject subject = SecurityUtils.getSubject();
if(subject.isRemembered()){
return "/index";
}
return "/login";
}
 
(如果想测试AfterThrowing,可以在方法中主动抛出异常)
打印结果为:
      

around 环绕增强,相当于MethodInterceptor
before 标识一个前置增强方法,相当于BeforeAdvice的功能
=============
after final增强,不管是抛出异常或者正常退出都会执行
afterReturn 后置增强,相当于AfterReturningAdvice,方法退出时执行

推荐阅读