aop主要用于日志记录,跟踪,优化和监控
下面是来自慕课网学习的一些案例,复制黏贴就完事了,注意类和方法的位置
pom添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
package com.tx.gelv.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* @author:hgt
* @version:1.0
* @date:2020/5/14
* @description:com.tx.gelv.aspect
* aop 面向切面编程
*/
/**
* @Component
* 引入到spring容器内
*/
@Aspect
@Component
public class HttpAspect {
// /**
// * **********************type1*******************************************
// */
// //对方法和类进行拦截,在目标运行之前
// @Before("execution(public * com.tx.gelv.controller.Test.index(..))")
// public void beforelogs(){
// System.out.println("1111");
// }
//
// //对方法和类进行拦截,在目标运行之后
// @After("execution(public * com.tx.gelv.controller.Test.index(..))")
// public void afterlogs(){
// System.out.println("2222");
// }
/**
* ***************************type2**********************************
*/
//自带日志log4j
private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
@Pointcut("execution(public * com.tx.gelv.controller.Test.*(..))")
public void log(){
}
@Before("log()")
public void before(JoinPoint joinPoint){
logger.info("***********aspect********before*************start***************");
ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//url
logger.info("url={}",request.getRequestURL());
//method
logger.info("method={}",request.getMethod());
//ip
logger.info("ip={}",request.getRemoteAddr());
//类方法
logger.info("class-method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
//参数
logger.info("args:{}",joinPoint.getArgs());
logger.info("***********aspect********before**********stop*******************");
}
@After("log()")
public void after(){
logger.info("22222222");
}
/**
* 用于返回对象信息
* @param object
*/
@AfterReturning(returning = "object",pointcut = "log()")
public void doAfterReturning(Object object){
logger.info("response={}",object);
}
}
实现图片:
后续将持续更新