Spring Boot學習——AOP編程的簡單實現

       首先應該明白一點,AOP是一種編程範式,是一種程序設計思想,與具體的計算機編程語言無關,因此不止是Java,像.Net等其餘編程語言也有AOP的實現方式。AOP的思想理念就是將通用邏輯從業務邏輯中分離出來。java

       本文將經過一個HTTP請求的例子簡單的講解Spring Boot中AOP的應用,步驟以下:web

       第一步,添加依賴spring

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

       第二步,建立AOP方法的類編程

package *; //本身定義

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;


@Aspect
@Component
public class HttpAspect {
    //使用org.slf4j.Logger,這是Spring實現日誌的方法
    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    /**
     * 定義AOP掃描路徑
     * 第一個註解只掃描aopTest方法
     */
    //@Pointcut("execution(public * com.aston.reader.controller.StudentController.aopTest())")
    @Pointcut("execution(public * com.aston.reader.controller.StudentController.*())")
    public void log(){}

    /**
     * 記錄HTTP請求開始時的日誌
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //URL
        logger.info("url={}", request.getRequestURI());
        //method
        logger.info("method={}", request.getMethod());
        //ip
        logger.info("ip={}",request.getRemoteAddr());
        //類方法
        logger.info("class={} and method name = {}",joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName());
        //參數
        logger.info("參數={}",joinPoint.getArgs());
    }

    /**
     * 記錄HTTP請求結束時的日誌
     */
    @After("log()")
    public void doAfter(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logger.info("url = {} end of execution", request.getRequestURL());
    }

    /**
     * 獲取返回內容
     * @param object
     */
    @AfterReturning(returning = "object",pointcut = "log()")
    public void doAfterReturn(Object object){
        logger.info("response={}",object.toString());
    }
}

       第三步,建立試驗方法app

package *; //本身定義

import org.springframework.web.bind.annotation.*;

@RestController
public class StudentController {

    @GetMapping(value = "/aoptest")
    public String aopTest(){
        return " AOP test success!";
    }

}

       第四步,啓動程序,訪問 http://127.0.0.1:8080/aoptest 查看結果。編程語言

相關文章
相關標籤/搜索