Springboot中Aspect切面的实现方式(以记录日志为例)

Springboot Aspect切面的实现

今天我们来说说spring中的切面Aspect,这是Spring的一大优势。面向切面编程往往让我们的开发更加低耦合,也大大减少了代码量,同时呢让我们更专注于业务模块的开发,把那些与业务无关的东西提取出去,便于后期的维护和迭代。

好了,废话少说!我们直接步入正题

以系统日志为例

首先,我们先做一些准备工作。

1、新建一个Springboot工程

2、添加必要的依赖

AOP 必须

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

gson主要是我用于数据的处理,不是必须的

<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.1</version></dependency>

个人喜好

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope></dependency><dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional></dependency>

3、日志实体类和service

package com.space.aspect.bo; import lombok.Data; /** * 系统日志bo * @author zhuzhe * @date 2018/6/4 9:36 * @email 1529949535@qq.com */@Datapublic class SysLogBO {     private String className;    private String methodName;     private String params;     private Long exeuTime;     private String remark;     private String createDate;}package com.space.aspect.service; import com.space.aspect.bo.SysLogBO;import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Service; /** * @author zhuzhe * @date 2018/6/4 9:41 * @email 1529949535@qq.com */@Slf4j@Servicepublic class SysLogService {     public boolean save(SysLogBO sysLogBO){        // 这里就不做具体实现了        log.info(sysLogBO.getParams());        return true;    }}

4、定义日志注解

这里呢,我们记录日志使用注解的形式。所以,先定义一个注解

package com.space.aspect.anno;import java.lang.annotation.*; /** * 定义系统日志注解 * @author zhuzhe * @date 2018/6/4 9:24 * @email 1529949535@qq.com */@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface SysLog {    String value() default "";}

5、声明切面,完成日志记录

以上4点我们的准备工作已经完成。接下来就是重点了

这里需要你对AOP有一定的了解。起码知道切点表达式、环绕通知、前置通知、后置通知等。。。

package com.space.aspect.aspect;import com.google.gson.Gson;import com.space.aspect.anno.SysLog;import com.space.aspect.bo.SysLogBO;import com.space.aspect.service.SysLogService;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.aspectj.lang.reflect.MethodSignature;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import java.lang.reflect.Method;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List; /** * 系统日志切面 * @author zhuzhe * @date 2018/6/4 9:27 * @email 1529949535@qq.com */@Aspect  // 使用@Aspect注解声明一个切面@Componentpublic class SysLogAspect {    @Autowired    private SysLogService sysLogService;     /**     * 这里我们使用注解的形式     * 当然,我们也可以通过切点表达式直接指定需要拦截的package,需要拦截的class 以及 method     * 切点表达式:   execution(...)     */    @Pointcut("@annotation(com.space.aspect.anno.SysLog)")    public void logPointCut() {}     /**     * 环绕通知 @Around  , 当然也可以使用 @Before (前置通知)  @After (后置通知)     * @param point     * @return     * @throws Throwable     */    @Around("logPointCut()")    public Object around(ProceedingJoinPoint point) throws Throwable {        long beginTime = System.currentTimeMillis();        Object result = point.proceed();        long time = System.currentTimeMillis() - beginTime;        try {            saveLog(point, time);        } catch (Exception e) {        }        return result;    }     /**     * 保存日志     * @param joinPoint     * @param time     */    private void saveLog(ProceedingJoinPoint joinPoint, long time) {        MethodSignature signature = (MethodSignature) joinPoint.getSignature();        Method method = signature.getMethod();        SysLogBO sysLogBO = new SysLogBO();        sysLogBO.setExeuTime(time);        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");        sysLogBO.setCreateDate(dateFormat.format(new Date()));        SysLog sysLog = method.getAnnotation(SysLog.class);        if(sysLog != null){            //注解上的描述            sysLogBO.setRemark(sysLog.value());        }        //请求的 类名、方法名        String className = joinPoint.getTarget().getClass().getName();        String methodName = signature.getName();        sysLogBO.setClassName(className);        sysLogBO.setMethodName(methodName);        //请求的参数        Object[] args = joinPoint.getArgs();        try{            List<String> list = new ArrayList<String>();            for (Object o : args) {                list.add(new Gson().toJson(o));            }            sysLogBO.setParams(list.toString());        }catch (Exception e){ }        sysLogService.save(sysLogBO);    }}

6、测试

接下来,我们就来测试一下吧

package com.space.aspect.controller;import com.space.aspect.anno.SysLog;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController; /** * @author zhuzhe * @date 2018/6/4 9:47 * @email 1529949535@qq.com */@RestControllerpublic class TestController {    @SysLog("测试")    @GetMapping("/test")    public String test(@RequestParam("name") String name){        return name;    }}

启动项目,访问我们的test方法。

我们在service里打一个断点

可以看到,我们所需要的值都成功拿到了。

这样,我们就成功实现了使用Aspect实现切面记录日志。

源码:https://github.com/zhuzhegithub/springboot-aop-aspect

Springboot Aspect切面实现方法日志打印

项目每次写controller方法,都要在开始和结束打印一行日志表示方法开始和结束,每个方法都要写,太过于麻烦和重复,想到了spring的aop切面,所以使用@Aspect切面和自定义log注解实现了下切面日志打印.

AOP

AOP(Aspect Orient Programming),直译过来就是 面向切面编程。AOP 是一种编程思想,是面向对象编程(OOP)的一种补充,在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等等,这里主要是做一下方法的日志打印。

aop相关注解:

@Aspect:作用是把当前类标识为一个切面供容器读取

@Pointcut:Pointcut是植入Advice的触发条件。每个Pointcut的定义包括2部分,一是表达式,二是方法签名。方法签名必须是 public及void型。可以将Pointcut中的方法看作是一个被Advice引用的助记符,因为表达式不直观,因此我们可以通过方法签名的方式为 此表达式命名。因此Pointcut中的方法只需要方法签名,而不需要在方法体内编写实际代码。

@Around:环绕增强,相当于MethodInterceptor

@AfterReturning:后置增强,相当于AfterReturningAdvice,方法正常退出时执行

@Before:标识一个前置增强方法,相当于BeforeAdvice的功能,相似功能的还有

@AfterThrowing:异常抛出增强,相当于ThrowsAdvice

@After: final增强,不管是抛出异常或者正常退出都会执行

自定义注解

声明一个注解要用到的东西

修饰符:访问修饰符必须为public,不写默认为pubic;

关键字:关键字为@interface;

注解名称:注解名称为自定义注解的名称,使用时还会用到;

注解类型元素:注解类型元素是注解中内容,可以理解成自定义接口的实现部分;

代码:

自定义log注解代码

/** * 日志注解 * * Target:用于明确注解用于目标类的哪个位置 * Retention:用于标识自定义注解的生命周期 *            RUNTIME:生命周期持续到运行时,能够通过反射获取到 * Documented:用于标识自定义注解能够使用javadoc命令生成关于注解的文档 * * @author xxx * @date 2020/xx/xx */@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface LogMessage {     /**     * 使用value值,在使用注解的时候,不需要写@LogMessage(value=xxx),直接写@LogMessage(xxx)即可     */    String value() default "";     /**     * 别名使用value,所以在使用注解时,既可以写@LogMessage(xxx),也可以写@LogMessage(description=xxx)     */    @AliasFor("value")    String description() default "";     /**     * 是否打印参数     */    boolean parameterPrint() default true;}

apsect切面类注解

/** * 日志切面类 * Aspect :作用是把当前类标识为一个切面供容器读取 * * @author xxx * @date 2020/xx/xx */@Slf4j@Aspect@Componentpublic class LogAspect {     /**     * 前置增强,目标方法执行之前执行     * within:用于匹配所以持有指定注解类型内的方法     * annotation:用于匹配当前执行方法持有指定注解的方法     * within(com.xxx.xxx..*) com.xxx.xxx包及子包下的任何方法执行     *     * @param joinPoint     * @param logManage     * @return void     * @author xxx     * @date 2020/xx/xx     */    @Before("within(com.xxx.xxx..*) && @annotation(logManage)")    public void addBeforeLogger(JoinPoint joinPoint, LogMessage logManage) {        log.info("[{}] Start", logManage.value());        // 处理参数        try {            if (logManage.parameterPrint()) {                Object[] args = joinPoint.getArgs(); // 参数值                String[] argNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();                Map<String, Object> paramsMap = new HashMap<>();                StringBuilder sb = new StringBuilder();                if (args != null && args.length > 0) {                    for (int i = 0; i < args.length; i++) {                        paramsMap.put(argNames[i], args[i] != null ? args[i].toString() : "");                    }                     for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {                        sb.append(entry.getKey()).append(":").append(entry.getValue()).append(";");                    }                }                log.info("[方法名称:{},方法参数:{}", ((MethodSignature) joinPoint.getSignature()).getMethod().getName(), sb.toString());            }        } catch (Exception e) {            log.info("切面日志打印异常!");        }    }     /**     * 返回增强,目标方法正常执行完毕时执行     *     * within:用于匹配所以持有指定注解类型内的方法     * annotation:于匹配当前执行方法持有指定注解的方法     * within(com.xxx.xxx..*) com.xxx.xxx 包及子包下的任何方法执行     *     * @param joinPoint     * @param logManage     * @return void     * @author xxx     * @date 2020/xx/xx     */    @AfterReturning("within(com.xxx.xxx..*) && @annotation(logManage)")    public void addAfterReturningLogger(JoinPoint joinPoint, LogMessage logManage) {        log.info("[{}] End", logManage.value());    }}

controller中使用

@LogMessage("测试日志打印")@GetMapping(value = "/test", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)public void xxx() { log.info("test");}

这样在方法执行前和返回后都会打印日志,只需要在想要打印日志的方法上添加@LogMessage(“”)注解就可以了。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

一个真正的人对困难的回答是战斗,

Springboot中Aspect切面的实现方式(以记录日志为例)

相关文章:

你感兴趣的文章:

标签云: