目录
1 前言
在我们的项目中,项目表可能会有一些公共的字段需要我们的赋值,比如更新时间(updateTime)等。如果我们每次都手动的进行设置,那么代码将比较冗余且不易于维护。接下来我将介绍公共字段的自动填充,来优雅的解决这个问题。
2 使用方法
2.1 自定义枚举类
该步骤用于标识数据库的操作类型,如下:
public enum OperationType {
/**
* 更新操作
*/
UPDATE,
/**
* 插入操作
*/
INSERT
}
2.2 自定义注解@AutoFill
该步骤用于标识需要进行公共字段自动填充的方法,如下:
@Target(ElementType.METHOD) //表示该注解是用于方法上的
@Retention(RetentionPolicy.RUNTIME) //表示该注解一直保留到运行时
public @interface AutoFill {
// 自动填充的操作类型: Update,Insert
OperationType value();
}
2.3 自定义切面类并设定切入点
@Aspect
@Component
public class AutoFillAspect {
/**
* 符合以下要求的为切入点:
* 1.mapper包下任意类中参数和返回值任意的所有方法
* 2.方法上必须含我们刚才定义的AutoFill注解
*/
@Pointcut("execution(* com.xxx.mapper.*.*(..)) && @annotation(com.xxx.annotation.AutoFill)")
public void autoFillPointCut() {}
}
2.4 切面类中设置前置通知,对公共字段赋值
@Aspect
@Component
public class AutoFillAspect {
@Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
public void autoFillPointCut() {}
/**
* 前置通知,在通知中进行公共字段的赋值
*/
@Before("autoFillPointCut()")
public void autoFill(JoinPoint joinPoint) {
//获取拦截方法上的操作类型
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
OperationType operationType = autoFill.value();
//获取拦截方法的参数-实体对象,默认第一个参数为我们需要的对象
Object[] args = joinPoint.getArgs();
if (args == null || args.length == 0) {
return;
}
Object entity = args[0];
//准备赋值的数据
LocalDateTime now = LocalDateTime.now();
Long currentId = BaseContext.getCurrentId();
//赋值
if (operationType == OperationType.UPDATE) {
try {
Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
//通过反射为对象属性赋值
setUpdateTime.invoke(entity,now);
setUpdateUser.invoke(entity,currentId);
} catch (Exception e) {
e.printStackTrace();
}
} else if (operationType == OperationType.INSERT) {
//其它代码...
}
}
}
2.5 在方法上添加自定义注解
@Mapper
public interface MyClassMapper {
/**
* 根据id修改分类
* @param category
*/
@AutoFill(value = OperationType.UPDATE)
void update(MyClass myClass);
}
这样我们就不需要在服务层中为手动添加相关内容了,解放双手。
3 最后
另附赠注释如下,愿永无bug:
/*
* _oo0oo_
* o8888888o
* 88" . "88
* (| -_- |)
* 0\ = /0
* ___/`---'\___
* .' \\| |// '.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' |_/ |
* \ .-\__ '-' ___/-. /
* ___'. .' /--.--\ `. .'___
* ."" '< `.___\_<|>_/___.' >' "".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `_. \_ __\ /__ _/ .-` / /
* =====`-.____`.___ \_____/___.-`___.-'=====
* `=---='
*
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* 佛祖保佑 永不宕机 永无BUG
*
* 佛曰:
* 写字楼里写字间,写字间里程序员;
* 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠;
* 酒醉酒醒日复日,网上网下年复年。
* 但愿老死电脑间,不愿鞠躬老板前;
* 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱;
* 不见满街漂亮妹,哪个归得程序员?
*/