AOP
[toc]
创建切面方式一:
@Aspect
@Component
public class HttpAspect {
@Before("execution(public * com.example.HelloController.*(..))")
public void logBefore() {
System.out.print("logBefore");
}
@After("execution(public * com.example.HelloController.*(..))")
public void logAfter() {
System.out.print("logAfter");
}
}
创建切面方式二:(抽取切点出来,减少重复代码)
@Aspect
@Component
public class HttpAspect {
@Pointcut("execution(public * com.example.HelloController.*(..))")
public void log() {
}
@Before("log()")
public void logBefore() {
System.out.print("logBefore");
}
@After("log()")
public void logAfter() {
System.out.print("logAfter");
}
}
@Aspect
@Component
public class HttpAspect {
public static Logger logger = LoggerFactory.getLogger(HttpAspect.class);
@Pointcut("execution(public * com.example.HelloController.*(..))")
public void log() {
}
@Before("log()")
public void logBefore(JoinPoint joinPoint) {
logger.info("logBefore");
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
logger.info("url={}", request.getRequestURL());
logger.info("method={}", request.getMethod());
logger.info("ip={}", request.getRemoteAddr());
logger.info("class.method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info("args={}", joinPoint.getArgs());
}
@After("log()")
public void logAfter() {
logger.info("logAfter");
}
@AfterReturning(returning = "object", pointcut = "log()")
public void logAfterReturning(Object object) {
logger.info("response={}", object.toString());
}
}
输出日志:
logBefore
url=http://localhost:8080/updatePerson
method=PUT
ip=0:0:0:0:0:0:0:1
class.method=com.example.HelloController.updatePerson
args=10
m person person0_ where person0_.id=?
logAfter
response=com.example.Person@34b98c82