Spring Boot 進階之Web進階 學習 - 使用AOP處理請求

AOP 面向切面編程java

1.添加aop依賴spring

pom.xml中添加編程

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

2.建立切面文件 HttpAspect.java
@Aspect    //切面 註解
@Component
public class HttpAspect {

private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class); //日誌記錄

@Pointcut("execution(public * com.example.girl.controller.GirlController.*(..))")
private void log(){
}


@Before("log()")
public void doBefor(JoinPoint joinPoint){

ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = attributes.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 doAfter(){
logger.info("doAfter.......");
}

@AfterReturning(returning = "object",pointcut = "log()") public void doAfterReturning(Object object){ logger.info("response={}",object.toString()); }}
相關文章
相關標籤/搜索