1. 程式人生 > >SpringBoot使用AOP

SpringBoot使用AOP

一.pom新增依賴

<!--AOP-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
            <version>RELEASE</version>
        </dependency>

二.建立切面類

package com.example.demo.aspect;

import com.example.demo.exception.MyException;
import com.example.demo.utils.ResultUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.logging.Logger;

/* *
 * Created by Ay on 2018/9/20
 */
@Aspect
@Component
public class ControllerAspect {


    @Pointcut("execution(public * com.example.demo.controller.TestController.errorTest(..))")
    public void check() {

    }

    @Before(value = "check()")
    public void checkBefore(JoinPoint joinPoint)
    {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        System.out.println("===============請求內容===============");
        System.out.println("請求地址:"+request.getRequestURL().toString());
        System.out.println("請求方式:"+request.getMethod());
        System.out.println("請求類方法:"+joinPoint.getSignature());
        System.out.println("請求類方法引數:"+ Arrays.toString(joinPoint.getArgs()));
        //檢查許可權
        HttpSession session = request.getSession();
        if(session.getAttribute("user")==null) {
            throw new MyException(-1,"無許可權訪問");
        }

    }

    @After(value = "check()")
    public void checkAfter() {
        System.out.println("aop after");
    }

}

@Aspect宣告這是一個切面類
@Pointcut切點指明要切入的方法,check是簽名
JoinPoint可以獲得要請求的方法和請求的引數

三.測試程式碼

@RequestMapping(value = "error/{id}")
    public Object errorTest(@PathVariable("id") Integer id) {
        if(id == 0){
            throw new MyException(-1,"除0");
        }
        int result = 10 / id;
        return ResultUtil.success(result);
    }

    @RequestMapping(value = "login")
    @ResponseBody
    public Object loginTest(@RequestParam("username") String username, @RequestParam("password") String password,
                            HttpSession session){
        if("admin".equals(username) && "admin".equals(password)){
            session.setAttribute("user",username);
            return ResultUtil.success();
        }
        return ResultUtil.error(-1,"登入失敗");
    }

列印內容
在這裡插入圖片描述
AOP通常可用於許可權檢查及訪問日誌