注解的基本语法 定义注解使用interface关键字来定义注解public interface AutoFill { }元注解元注解是用来注解其他注解的注解Java提供了以下几种元注解Target - 指定注解可以应用的目标元素类型Retention - 指定注解的保留策略Documented - 表示注解应该被包含在Javadoc中Inherited - 表示注解可以被继承Target(ElementType.METHOD) Retention(RetentionPolicy.RUNTIME) public interface AutoFill { /** * 数据库操作类型INSERT、UPDATE */ OperationType value(); }示例代码展示了一个用于公共字段自动填充的自定义注解Target明确注解可在方法上使用Retention明确在程序运行时可见。注解元素注解中可以定义元素这些元素可以有默认值public enum OperationType { /** * 更新操作 */ UPDATE, /** * 插入操作 */ INSERT }示例自定义注解中的value方法则用来返回上示枚举类型数据明确 使用该注解的方法 的作用使用方式如下/** * 更新员工信息 * param employee */ AutoFill(OperationType.UPDATE) void updateById(Employee employee);当注解只有一个方法且方法名为 value 时使用时可以省略方法名如果方法不叫 value就必须明确指定方法名Target(ElementType.METHOD) Retention(RetentionPolicy.RUNTIME) public interface AutoFill { /** * 数据库操作类型INSERT、UPDATE */ OperationType type(); }/** * 更新员工信息 * param employee */ AutoFill(type OperationType.UPDATE) void updateById(Employee employee);自定义注解的使用通过反射处理注解我们可以使用反射机制在运行时读取和处理注解Aspect Component Slf4j public class AutoFillAspect { /** * 公共字段自动填充切入点 */ Pointcut(execution(* com.sky.mapper.*.*(..)) annotation(com.sky.annotation.AutoFill)) public void autoFillPointCut() {} /** * 公共字段自动填充 */ Before(autoFillPointCut()) public void autoFill(JoinPoint joinPoint) throws Throwable { log.info(公共字段自动填充通知开始); MethodSignature signature (MethodSignature)joinPoint.getSignature(); AutoFill autoFill signature.getMethod().getAnnotation(AutoFill.class); // 获取数据库操作类型 Enum operationType autoFill.value(); // 从ThreadLocal中获取当前登录用户的id Long currentId BaseContext.getCurrentId(); // 获取当前时间 LocalDateTime now LocalDateTime.now(); // 从joinPoint中获取参数 Object[] args joinPoint.getArgs(); if(argsnull || args.length0){ return; } // 从参数中获取实体对象 Object entity args[0]; // 调用实体对象的方法设置创建时间、创建人、更新时间、更新人 if(operationTypeOperationType.INSERT){ try{ Method setCreateTime entity.getClass().getDeclaredMethod(setCreateTime, LocalDateTime.class); Method setUpdateTime entity.getClass().getDeclaredMethod(setUpdateTime, LocalDateTime.class); Method setCreateUser entity.getClass().getDeclaredMethod(setCreateUser, Long.class); Method setUpdateUser entity.getClass().getDeclaredMethod(setUpdateUser, Long.class); setCreateTime.invoke(entity, now); setUpdateTime.invoke(entity, now); setCreateUser.invoke(entity, currentId); setUpdateUser.invoke(entity, currentId); }catch (Exception e){ log.error(公共字段自动填充通知异常, e); } }else if(operationTypeOperationType.UPDATE){ try{ Method setUpdateTime entity.getClass().getDeclaredMethod(setUpdateTime, LocalDateTime.class); Method setUpdateUser entity.getClass().getDeclaredMethod(setUpdateUser, Long.class); setUpdateTime.invoke(entity, now); setUpdateUser.invoke(entity, currentId); }catch (Exception e){ log.error(公共字段自动填充通知异常, e); } } }