Spring Boot笔记九:AOP面向切面编程

我参考的这篇文章,以验证身份为例讲解了什么是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

posted @ 2019-02-08 11:10  蜀云泉  阅读(468)  评论(0编辑  收藏  举报