应用场景
在一些业务类的创建中,我们需要反复对不同的类的同一个属性进行赋值,那么问题就出现了 **代码冗余**如何解决呢
思路:利用aop创造一个切面
如何创造一个切面呢
实质上就是扫描加设置增强位置 那么如何扫描到对应的赋值方法上呢 这里需要用到自定义注解了 自定义注解://这里的OperationType 是定义的一个枚举类型,value是里面的枚举常量,在我们标识对应的方法中可以使用不同的常量来执行不同的判断
//表明作用对象是方法
@Target(value = ElementType.METHOD)
//运行时实现的,aop必写
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoFill {OperationType value();
}
注解完成
注解完成,开始操刀aop切面
@Aspect//切面需要加的注解
@Component
@Slf4j
public class AutoFillAspect {
//这里标识,此切面的范围,也就是需要被增强的类,为了准确定位,我们还需要确认注解也在上面,使用poincut是为了减少冗余代码@Pointcut("execution(* com.sky.mapper.*.*(..))&&@annotation(com.sky.annotation.AutoFill)")public void autoFillPointcut(){}
//before在执行前进行一个增强的操作,参数基本都是JoinPoint@Before("autoFillPointcut()")public void autoFill(JoinPoint joinPoint){log.info("首位增强");
//通过参数获取签名MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//通过签名获取自定义注解的值AutoFill aution = signature.getMethod().getAnnotation(AutoFill.class);OperationType value = aution.value();
//通过参数获取对应的类Object[] args = joinPoint.getArgs();if(args.length==0||args== null){return;}Object arg = args[0];
//通过判断注解值后,getDeclaredMethod调用类里面的赋值方法if (value==OperationType.INSERT) {LocalDateTime updateTime = LocalDateTime.now();LocalDateTime createTime=LocalDateTime.now();Long createUser= BaseContext.getCurrentId();Long updateUser=BaseContext.getCurrentId();try {arg.getClass().getDeclaredMethod("setUpdateTime",updateTime.getClass());arg.getClass().getDeclaredMethod("setCreateTime",createTime.getClass());arg.getClass().getDeclaredMethod("setCreateUser",createUser.getClass());arg.getClass().getDeclaredMethod("setUpdateUser",updateUser.getClass());} catch (Exception e) {throw new RuntimeException(e);}}else if(value==OperationType.UPDATE){LocalDateTime updateTime = LocalDateTime.now();Long updateUser=BaseContext.getCurrentId();try {arg.getClass().getDeclaredMethod("setUpdateUser",updateUser.getClass());arg.getClass().getDeclaredMethod("setUpdateTime",updateTime.getClass());} catch (Exception e) {throw new RuntimeException(e);}}}
}