程序员社区

SpringBoot笔记(二):基于注解,实现日志保存功能

1.添加Maven依赖(引入AOP依赖包)

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

2.自定义注解,本文定义为 LogAnnotation

@Target({ElementType.METHOD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAnnotation {

    //具体属性,根据需求自定义
    String code() default "";
    String name() default "";
    String description() default "";
}

3.编写日志切面类(完成日志的保存操作)

@Aspect //声明这是一个切面Bean,这个类被声明为是一个需要动态织入到我们的虚拟切面中的类
@Component //声明这是一个组件,声明这个类是被SpringIOC容器来管理的,如果不声明,就无法做到自动注入
@EnableAspectJAutoProxy(proxyTargetClass = true) //开启AspectJ 自动代理模式,如果不填proxyTargetClass=true,默认为false
public class LogAnnotationAspect {

    private static final Logger LOG = Logger.getLogger(LogAnnotationAspect.class);

    @Pointcut("@annotation(com.demo.springboot_mongodb.annotation.LogAnnotation)")
    public void pointcutConfig(){}

    @Before("pointcutConfig()")
    public void before(JoinPoint joinpoint) {
        LOG.info("前置通知---方法前执行" + joinpoint);
        //伪代码,执行日志保存操作:logService.save(xxx)
        LOG.info("执行日志写入日到MySQL数据库");
    }

    //如有需要,可做操作
    @After("pointcutConfig()")
    public void after(JoinPoint joinpoint) {
        //LOG.info("后置通知---方法后执行" + joinpoint);
    }

    //如有需要,可做操作
    @AfterReturning("pointcutConfig()")
    public void afterReturn(JoinPoint joinpoint) {
        //LOG.info("后置返回通知---调用获得返回值后执行" + joinpoint);
    }

    //如有需要,可做操作
    @AfterThrowing("pointcutConfig()")
    public void afterThrows(JoinPoint joinpoint) {
        //LOG.info("抛出异常后,执行" + joinpoint);
    }
}

4.在Controller上,添加@LogAnnotation注解

/**
 * 查询全部
 * @return
 */
@RequestMapping("findAll")
@ResponseBody
@LogAnnotation   //参数如有默认值,可不填
public List<User> findAll(){
    List<User> users = mongoDao.findAll();
    return users;
}

/**
 * 普通条件查询
 */
@RequestMapping("find")
@ResponseBody
@LogAnnotation(code = "1001", name = "Controller名称", description = "这里是一些描述信息")
public List<User> find(){
    List<User> users = mongoDao.find();
    return users;
}

5.通过反射机制 && 切入点JoinPoint ,可以获取注解上面的参数,方法如下

public static Map<String,String> getParameter(JoinPoint joinPoint){
    Map<String,String> annotionMap = Maps.newHashMap();
    Class targetClass = joinPoint.getTarget().getClass();
    String methodName = joinPoint.getSignature().getName();
    Object[] arguments = joinPoint.getArgs();
    Method[] methods = targetClass.getMethods();
    String module = "";
    for (Method method : methods) {
        if (method.getName().equals(methodName)) {
            Class[] clazzs = method.getParameterTypes();
            if (clazzs.length == arguments.length) {
                annotionMap.put("code",method.getAnnotation(LogAnnotation.class).code());
                annotionMap.put("name",method.getAnnotation(LogAnnotation.class).name());
                annotionMap.put("description",method.getAnnotation(LogAnnotation.class).module());
                break;
            }
        }
    }
    return annotionMap;
}

 


SpringBoot基于注解实现日志保存,介绍到此为止

如果本文对你有所帮助,那就给我点个赞呗 ^_^ 

End

赞(0) 打赏
未经允许不得转载:IDEA激活码 » SpringBoot笔记(二):基于注解,实现日志保存功能

一个分享Java & Python知识的社区