springboot切面编程范例

相较与古老的ssm项目,springboot项目的切面编程几乎不用配置。开箱即用。
 

依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

 

注解

import java.lang.annotation.*;
 
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @
interface SysLogger { String action() default ""; String content() default ""; }

 

切面类

@Aspect
@Component
public class MyNewAspect {
 
    //整个包下的所有
    @Pointcut("execution(* com.***.***.controller.*.*(..))")
    public void point(){}
 
    //基于注解的切点
    //@annotation(com.***.***.annotation.SysLogger)
    @Pointcut("@annotation(com.***.***.annotation.SysLogger)")
    public void point0(){}
 
    // 期望在某个方法执行前做一些处理,叫做前置通知
    @Before(value="point()")
    public void begin(JoinPoint joinPoint){
        String name =joinPoint.getSignature().getName();
        System.out.println(name + "方法开始执行...");
        // 添加处理代码
        // ...
        // 以上是处理代码
    }
 
    // 期望在某个方法执行后做一些处理,叫做后置最终通知
    @After(value = "point()")
    public void end(JoinPoint joinPoint){
        String name = joinPoint.getSignature().getName();
        System.out.println(name + "方法执行结束...");
        // 添加处理代码
        // ...
        // 以上是处理代码
    }
 
    // 期望在某个方法返回时做一些处理,叫做后置返回通知
    @AfterReturning(value = "point()" , returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result){
        String name = joinPoint.getSignature().getName();
        System.out.println(name + "方法返回值为:" + result);
        // 添加处理代码
        // ...
        // 以上是处理代码
    }
 
    // 期望在某个方法抛出异常时做一些处理,叫做后置异常通知
    @AfterThrowing(value = "point()" , throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Exception e){
        String name = joinPoint.getSignature().getName();
        System.out.println(name + "方法抛出异常:" + e.getClass().getName());
        // 添加处理代码
        // ...
        // 以上是处理代码
    }
 
    // 期望在某个方法执行时做一些处理,叫做环绕通知
    // 这个通知功能强大且比较灵活。
    @Around("point0()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        // 添加处理代码
        // ...
        // 以上是处理代码
        return proceedingJoinPoint.proceed();
    }
}

 

 
posted @ 2020-01-29 20:10  itwetouch  阅读(480)  评论(0编辑  收藏  举报