sprintboot 配置AOP

简介:

  SpringBoot框架中对AOP有很好的支持,简单AOP概念:

  JoinPoint(连接点):类里面可以被增强的方法即为连接点,例如,想修改哪个方法的功能,那么该方法就是一个连接点。

  Pointcut(切入点):对JoinPoint进行拦截的定义即为切入点,例如拦截所有insert开始的方法,这个定义即为切入点。

  Advice(通知):拦截到Joinpoint之后要做的事就是通知,分为前置,后置,异常,环绕,返回通知.

  Aspect(切面):Pointcut和Advice的结合。

  Target(目标对象):要增强的类称为Target.

SpringBoot中,首先引入aop依赖:

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

controller:

@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/getUserById/{id}")
    public String getUserById(@PathVariable("id") Integer id) {
        return userService.getUserById(id);
    }

    @GetMapping("/deleteUserById")
    public void deleteUserById(Integer id) {
        userService.deleteUserById(id);
    }
}

Service:

@Service
public class UserService {
    public String getUserById(Integer id) {
        System.out.println("get..."+id);
        return "user";
    }
    public void deleteUserById(Integer id) {
        int i = 1 / 0;
        System.out.println("delete...");
    }
}

Aspect:

@Component
@Aspect
public class LogAspect {
  //切入点:返回类型 包+类+方法(参数)
  @Pointcut("execution(* org.sang.aop.service.*.*(..))")
    public void pc1() {
    }

    @Before(value = "pc1()")
    public void before(JoinPoint jp) {
        String name = jp.getSignature().getName();
        System.out.println(name + "方法开始执行...");
    }

    @After(value = "pc1()")
    public void after(JoinPoint jp) {
        String name = jp.getSignature().getName();
        System.out.println(name + "方法执行结束...");
    }

    @AfterReturning(value = "pc1()", returning = "result")
    public void afterReturning(JoinPoint jp, Object result) {
        String name = jp.getSignature().getName();
        System.out.println(name + "方法返回值为:" + result);
    }

    @AfterThrowing(value = "pc1()",throwing = "e")
    public void afterThrowing(JoinPoint jp,Exception e) {
        String name = jp.getSignature().getName();
        System.out.println(name+"方法抛异常了,异常是:"+e.getMessage());
    }

    @Around("pc1()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        return pjp.proceed();
    }

}

正常访问:

http://localhost:8080/getUserById/2

 执行顺序:前置--service中的方法--后置--正常返回

异常:

http://localhost:8080/deleteUserById

 执行顺序:前置--后置--异常返回

猜你喜欢

转载自www.cnblogs.com/atomgame/p/12510122.html