1. 程式人生 > >Spring Boot筆記九:AOP面向切面編程

Spring Boot筆記九:AOP面向切面編程

www. .cn frame time 環繞 etag valid org pointcut

我參考的這篇文章,以驗證身份為例講解了什麽是AOP AOP

這裏只講解一下怎麽去實現AOP

新建一個類,叫HttpAspect用來切面

package com.vae.springboot.study.aspect;

import jdk.nashorn.internal.ir.RuntimeNode;
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 {

    //日誌
    Logger logger=LoggerFactory.getLogger(getClass());
    private RuntimeNode attributes;
    
    @Pointcut("execution(public * com.vae.springboot.study.Controller.HelloController.*(..))")
    public void log(){ }

    @Before("log()")
    public void doBefore(){
        ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();

        logger.info("假裝我在這裏驗證了用戶身份");
        //url
        logger.info("url={}",request.getRequestURI());
        //方法
        logger.info("method={}",request.getMethod());
        //ip
        logger.info("ip={}",request.getRemoteAddr());
        //類方法
        //logger.info("class_method={}",joinPoint.getSignature());
        //參數
        //logger.info("arg={}",joinPoint.getArgs());
    }
    @After("log()")
    public void doAfter(){
        logger.info("假裝我在這裏處理最後的事情");
    }
}

這裏面需要講的東西就是@Aspect註解

@Aspect

作用是把當前類標識為一個切面供容器讀取

@Before
標識一個前置增強方法,相當於BeforeAdvice的功能,相似功能的還有

@AfterReturning

後置增強,相當於AfterReturningAdvice,方法正常退出時執行

@AfterThrowing

異常拋出增強,相當於ThrowsAdvice

@After

final增強,不管是拋出異常或者正常退出都會執行

@Around

環繞增強,相當於MethodInterceptor

@DeclareParents

引介增強,相當於IntroductionInterceptor

看一下我們的Controller

package com.vae.springboot.study.Controller;

import com.vae.springboot.study.bean.Person;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.Map;

@Controller
public class HelloController {

    @PostMapping("/test")
    public String test(@Valid Person person, BindingResult bindingResult){
        System.out.println("test方法");
        if (bindingResult.hasErrors()) {
            System.out.println(bindingResult.getFieldError().getDefaultMessage());
            return null;
        }
        person.setName(person.getName());
        person.setAge(person.getAge());
        return "Vae";
    }


}

運行,然後使用PostMan執行一下http://localhost:8080/test

技術分享圖片

Spring Boot筆記九:AOP面向切面編程