springboot面向切面编程

 使用注解的方式可能要比使用配置文件要慢,因为注解要调用反射,贼耗时,但是你不用再去在配置文件上费心。实际上,在实际工作时,大部分都是使用注解的方式。

 

什么是AOP
AOP就是通过动态为项目中某些类在运行过程中动态创建代理对象,在对象中完成附加功能,保证在处理业务时更加专注于自己的业务逻辑开发。
有以下几个概念:
1.通知(Advice)——给目标方法添加额外操作称之为通知,也可以称为增强
2.连接点(Joinpoint)——就是可以增强的地方(方法的前后某个阶段)
3.切入点(Pointcut)——实际增强的地方
4.切面(Aspect)——封装了通知和切入点用来横向插入的类
5.代理(Proxy)——将通知应用到目标类动态创建的对象
6.织入(Weaving)——将切面插入到目标从而生成代理对象的过程
————————————————
版权声明:本文为CSDN博主「worilb」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/worilb/article/details/114156126

1、引入springboot-aop集成jar

          Spring-boot-start-aop

 

 

2、application.yml中启用声明

#spring配置
spring:
  #切面启用
  aop:
    proxy-target-class: true
    auto: true

 

@Component
@Aspect //切面类注解
@Order(2)
public class AsceptTest {

    @Pointcut("execution(* com.study.service.UserService.eat(*))")
    private void Myeat(){};


    //前置通知。value匹配规则,也就是指定拦截的切入点(方法)
//    @Before(value = "execution(* com.study.service.UserService.eat(*))") // execution匹配某些方法效率,whithin匹配某些类(中的所有方法)
    @Before(value = "Myeat()")
    public void before(JoinPoint joinPoint){
        System.out.println("当前方法名: "+joinPoint.getSignature().getName());
        System.out.println("当前执行方法参数: "+joinPoint.getArgs()[0]);
        System.out.println("目标对象target: "+joinPoint.getTarget());
        System.out.println("前置增强——保姆做饭");
    }

    //后置通知
//    @After(value = "execution(* com.study.service.UserService.eat(*))")
    @After("Myeat()")
    public void after(JoinPoint joinPoint){
        System.out.println("当前方法名: "+joinPoint.getSignature().getName());
        System.out.println("当前执行方法参数: "+joinPoint.getArgs()[0]);
        System.out.println("目标对象target: "+joinPoint.getTarget());
        System.out.println("后置增强——保姆洗碗");
    }


    //环绕通知
    @Around(value = "execution(* com.study.service.UserService.out())" )
    public Object round(ProceedingJoinPoint joinPoint) throws Throwable { //环绕增强必须要获取ProceedingJoinPoint参数,
        System.out.println("当前方法名: "+joinPoint.getSignature().getName());
//        System.out.println("当前执行方法参数: "+joinPoint.getArgs()[0]); 目标对象没参数不可获取
        System.out.println("目标对象target: "+joinPoint.getTarget());
        System.out.println("环绕增强——保安开门"); //目标方法执行前
        Object proceed = joinPoint.proceed(); //执行目标方法
        System.out.println("环绕增强——保安关门"); //目标方法执行后
        return proceed; //返回目标方法执行结果
    }

    //异常通知
    @AfterThrowing(value = "within(com.study.service.UserService+)",throwing="e")
    public void ex(JoinPoint joinPoint,Exception e){
        System.out.println("出错了"+e.getMessage());
    }

    //返回通知,方法正常返回则生效
    @AfterReturning(value = "within(com.study.service.UserService+)",returning="result")
    public void ex(JoinPoint joinPoint,Object result){
        System.out.println(joinPoint.getSignature().getName()+ ":返回通知生效");
        System.out.println("返回了"+result);
    }


}

 

 

也可以使用注解

package cn.annotation;
 
import java.lang.annotation.*;
 
/**
 * Title: SystemControllerLog
 * @date 2018年8月31日
 * @version V1.0
 * Description:  自定义注解,拦截service
 */
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemServiceLog {
    String description() default "";
}

 

 

package cn.annotation;
 
import cn.pojo.Action;
import cn.pojo.User;
import cn.service.ActionService;
import cn.utils.IpUtils;
import cn.utils.JsonUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
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.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
 
/**
 * Title: SystemControllerLog
 * @date 2018年8月31日
 * @version V1.0
 * Description: 切点类
 */
@Aspect
@Component
@SuppressWarnings("all")
public class SystemLogAspect {
    //注入Service用于把日志保存数据库,实际项目入库采用队列做异步
    @Resource
    private ActionService actionService;
    //本地异常日志记录对象
    private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);
    //Service层切点
    @Pointcut("@annotation(cn.annotation.SystemServiceLog)")
    public void serviceAspect(){
    }
 
    //Controller层切点
    @Pointcut("@annotation(cn.oa.annotation.SystemControllerLog)")
    public void controllerAspect(){
    }
 
    /**
     * @Description  前置通知  用于拦截Controller层记录用户的操作
     * @date 2018年9月3日 10:38
     */
 
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        //读取session中的用户
        User user = (User) session.getAttribute("user");
 
        String ip = IpUtils.getIpAddr(request);
 
        try {
            //*========控制台输出=========*//
            System.out.println("==============前置通知开始==============");
            System.out.println("请求方法" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()));
            System.out.println("方法描述:" + getControllerMethodDescription(joinPoint));
            System.out.println("请求人:"+user.getUsername());
            System.out.println("请求ip:"+ip);
 
            //*========数据库日志=========*//
            Action action = new Action();
            action.setActionDes(getControllerMethodDescription(joinPoint));
            action.setActionType("0");
            action.setActionIp(ip);
            action.setUserId(user.getId());
            action.setActionTime(new Date());
            //保存数据库
            actionService.add(action);
 
        }catch (Exception e){
            //记录本地异常日志
            logger.error("==前置通知异常==");
            logger.error("异常信息:{}",e.getMessage());
        }
    }
 
    /**
     * @Description  异常通知 用于拦截service层记录异常日志
     * @date 2018年9月3日 下午5:43
     */
    @AfterThrowing(pointcut = "serviceAspect()",throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint,Throwable e){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        //读取session中的用户
        User user = (User) session.getAttribute("user");
        //获取请求ip
        String ip = IpUtils.getIpAddr(request);
        //获取用户请求方法的参数并序列化为JSON格式字符串
        String params = "";
        if (joinPoint.getArgs()!=null&&joinPoint.getArgs().length>0){
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                params+= JsonUtils.objectToJson(joinPoint.getArgs()[i])+";";
            }
        }
        try{
            /*========控制台输出=========*/
            System.out.println("=====异常通知开始=====");
            System.out.println("异常代码:" + e.getClass().getName());
            System.out.println("异常信息:" + e.getMessage());
            System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
            System.out.println("方法描述:" + getServiceMethodDescription(joinPoint));
            System.out.println("请求人:" + user.getUsername());
            System.out.println("请求IP:" + ip);
            System.out.println("请求参数:" + params);
            /*==========数据库日志=========*/
            Action action = new Action();
            action.setActionDes(getServiceMethodDescription(joinPoint));
            action.setActionType("1");
            action.setUserId(user.getId());
            action.setActionIp(ip);
            action.setActionTime(new Date());
            //保存到数据库
            actionService.add(action);
        }catch (Exception ex){
            //记录本地异常日志
            logger.error("==异常通知异常==");
            logger.error("异常信息:{}", ex.getMessage());
        }
    }
 
 
    /**
     * @Description  获取注解中对方法的描述信息 用于service层注解
     * @date 2018年9月3日 下午5:05
     */
    public static String getServiceMethodDescription(JoinPoint joinPoint)throws Exception{
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method:methods) {
            if (method.getName().equals(methodName)){
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length==arguments.length){
                    description = method.getAnnotation(SystemServiceLog.class).description();
                    break;
                }
            }
        }
        return description;
    }
 
 
 
    /**
     * @Description  获取注解中对方法的描述信息 用于Controller层注解
     * @date 2018年9月3日 上午12:01
     */
    public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();//目标方法名
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method:methods) {
            if (method.getName().equals(methodName)){
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length==arguments.length){
                    description = method.getAnnotation(SystemControllerLog.class).description();
                    break;
                }
            }
        }
        return description;
    }
}

 

 

开始使用

    1)@SystemControllerLog(description = "")

          注解加在控制器中方法上面,括号里写上操作描述

 

posted @ 2022-05-17 13:55  1156740846  阅读(880)  评论(0编辑  收藏  举报