springboot 实现 aop

  1. pom.xml 导入 springboot aop 依赖

	org.springframework.boot
	spring-boot-starter-aop

  1. 创建 aspect,在 execution 参数中写上被切的类
@Aspect
@Component
public class IndexAspect {
    private static final Logger logger = LoggerFactory.getLogger(IndexAspect.class);

    // 公用的切点,该类下所有方法
    @Pointcut("execution(public * com.example.IndexController.*(..))")
    public void log() {
        logger.info("调用 log() ");
    }

    // 使用log函数定义的 execution,不执行log()方法
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        logger.info("调用 doBefore");
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        logger.info("获取 request");
        HttpServletRequest request = attributes.getRequest();
        logger.info("获取 reponse");
        attributes.getResponse();
        logger.info("获取 session");
        attributes.getRequest().getSession();
        logger.info("获取 class:" + joinPoint.getSignature().getDeclaringTypeName().toString());
        logger.info("获取 args:" + joinPoint.getArgs());
    }

    // 获取返回值
    @AfterReturning(pointcut = "log()", returning = "object")
    public void doAfterReturning(Object object) {
        logger.info("获取返回值" + object.toString());
    }
}
  1. 启动项目,查看控制台日志
com.example.IndexAspect: 调用 doBefore
com.example.IndexAspect: 获取 request
com.example.IndexAspect: 获取 reponse
com.example.IndexAspect: 获取 session
com.example.IndexAspect: 获取 class:com.example.thymeleaf.IndexController
com.example.IndexAspect: 获取 args:
com.example.IndexAspect: index

参考:http://www.fengyunxiao.cn

你可能感兴趣的:(java,springboot,springboot2)