spring 的 切片Aspect

1.controller方法:

 @Aspect
 @Component
public class TimeAspect {

    @Around("execution(* com.sea.web.controller.UserController.*(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("time aspect start");
        //说明:ProceedingJoinPoint 可获取调用的方法的传入参数的值
        //如:http:localhost:8080/user/1
        //comtroller  方法:public User getInfo(@PathVarable String id)
        Object[] args = pjp.getArgs();
        for (Object arg : args) {
            System.out.println("arg is " + arg); //id 1
        }
        long start = new Date().getTime();
        // 此object 就是条用 方法的返回值  如:User  user= UserController.findUser(), 
         //该方法相当于过滤器中dofilter()方法
        Object object = pjp.proceed(); 
        
        System.out.println("time aspect 耗时:" + (new Date().getTime() - start));
        System.out.println("time aspect end");
        return object;
    }

}

//@Around  : 包含以下三种

 

 Before Advice

代用之前的处理

After Advice

调用之后的处理

Throw Advice

调用的时候抛出的异常处理

execution(* com.sea.web.controller.UserController.*(..))
execution :表示执行
第一个 * :返回值 ;这代表 无论为什么返回值都行
com.sea.web.controller.UserController: 表示那个类
第二个 * :表示方法:类下的所有方法
*(..) :所有方法,任何参数的方法都执行
 

Anotation注解规则:

  @Aspect表示注解的类是抽象的服务方法模块;

@Pointcut定义服务的使用规则,也就是服务方法要应用到目标类中哪些方法上。

@Pointcut("execution(*add*(..))") 第一个*表示不论是否有返回值,所有以add开头的方法,不管是否有参数。

private voidaddAddMethod(){};该方法只是注解模式中一个空的方法体,是一个模式化的方法定义结构,该方法不能有返回值,不能有任何参数,也不能对其进行实现。在Advice中要使用该方法名的标识。

Advice注解checkSecurity()方法,表示该方法是具体的服务方法,使用注解的方式,Advice不出现,而是使用上面理论部分提到的使用@After、@Befor、@Throw来表示,同时要在Advice中关联pointcut中定义的规则。

猜你喜欢

转载自www.cnblogs.com/lshan/p/9190954.html