问题引入
javaee开发的时候,新增字段,修改字段大都会涉及到创建时间(createtime),更改时间(updatetime),创建人(craeteuser),更改人(updateuser),如果每次都要自己去setter(),会比较麻烦,可以使用spring的aop,对于任意insert,update操作进行增强
解决步骤
主要依赖
如果使用了springboot,那就只需要导入这一个,这个框架对spring自带的aop框架进行了优化封装,更好用
事实上,还需要两个依赖,spring-context和spring-aop,不过springboot自带的有
<dependency>
<groupid>org.aspectj</groupid>
<artifactid>aspectjweaver</artifactid>
<version>1.9.4</version>
</dependency>
注释代码
给那些新增、修改功能中的设置时间、修改人的代码部分注释掉

自定义注解&使用
封装数据库操作类型
/**
* 数据库操作类型
*/
public enum operationtype {
/**
* 更新操作
*/
update,
/**
* 插入操作
*/
insert
}自定义注解
@target(elementtype.method)
@retention(retentionpolicy.runtime)
public @interface autofill {
// 数据库操作类型:update insert
operationtype value();
}给需要自动填充的方法加上注解
/**
* 新增员工
* @param employee
*/
@insert("insert into employee" +
"(name, username, password, phone, sex, id_number, create_time, update_time, create_user, update_user)" +
"values" +
"(#{name}, #{username}, #{password}, #{phone}, #{sex}, #{idnumber}, #{createtime}, #{updatetime}, #{createuser}, #{updateuser})")
@autofill(value = operationtype.insert)
void insert(employee employee);
/**
* 修改员工信息
* @param employee
*/
@autofill(value = operationtype.update)
void update(employee employee);
/**
* 根据id查询员工
* @param id
* @return
*/
@select("select * from employee where id = #{id}")
employee getbyid(long id);
/**
* 密码修改
* @param passwordeditdto
*/
@autofill(value = operationtype.update)
@update("update employee set `password` = #{newpassword} where `id` = #{empid} and `password` = #{oldpassword}")
void updatepwd(passwordeditdto passwordeditdto);通知类
@slf4j
@component
@aspect
public class autofillaspect {
/**
* 切面 && 指定切入点
*/
@pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.autofill)")
public void autofillpointcut(){}
/**
* 切面 && 此方法(autofill()) 在切入点之前执行
* @param joinpoint
*/
@before("autofillpointcut()")
public void autofill(joinpoint joinpoint) {
log.info("开始进行公共字段自动填充...");
// 拿到当前被拦截的方法上的数据库操作类型
methodsignature signature = (methodsignature)joinpoint.getsignature();// 拿到实现类的签名信息,不过我们只需要方法的签名信息,强转成methodsignature
autofill autofill = signature.getmethod().getannotation(autofill.class);// 获得签名对象的注解对象
operationtype operationtype = autofill.value(); // 拿到数据库操作类型
// 拿到当前被拦截方法的方法参数(新增、更改方法的参数一般都是实体类)
object[] args = joinpoint.getargs();
if (args == null || args.length == 0){ // 防止null,防止空参
return;
}
object entity = args[0]; // 这一行就要求,以后的新增、更改方法参数,实体类必须写在首形参位置
// 需填充的数据
localdatetime now = localdatetime.now();
long currentid = basecontext.getcurrentid();
// 根据当前不同的操作类型,使用反射为对应的属性赋值
if (operationtype == operationtype.insert) {
// 为4个公共字段赋值
try {
method setcreatetime = entity.getclass().getdeclaredmethod(autofillconstant.set_create_time, localdatetime.class);
method setupdatetime = entity.getclass().getdeclaredmethod(autofillconstant.set_update_time, localdatetime.class);
method setcreateuser = entity.getclass().getdeclaredmethod(autofillconstant.set_create_user, long.class);
method setupdateuser = entity.getclass().getdeclaredmethod(autofillconstant.set_update_user, long.class);
// 通过反射给对象属性赋值
setcreatetime.invoke(entity, now);
setupdatetime.invoke(entity, now);
setcreateuser.invoke(entity, currentid);
setupdateuser.invoke(entity, currentid);
} catch (exception e) {
e.printstacktrace();
}
} else if (operationtype == operationtype.update) {
// 为2个公共字段赋值
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();
}
}
}
}依赖相关类
公共字段自动填充相关常量
/**
* 公共字段自动填充相关常量
*/
public class autofillconstant {
/**
* 实体类中的方法名称
*/
public static final string set_create_time = "setcreatetime";
public static final string set_update_time = "setupdatetime";
public static final string set_create_user = "setcreateuser";
public static final string set_update_user = "setupdateuser";
}线程空间上下文
public class basecontext {
public static threadlocal<long> threadlocal = new threadlocal<>();
public static void setcurrentid(long id) {
threadlocal.set(id);
}
public static long getcurrentid() {
return threadlocal.get();
}
public static void removecurrentid() {
threadlocal.remove();
}
}启动类加上注解@enableaspectjautoproxy
@springbootapplication
@enabletransactionmanagement //开启注解方式的事务管理
@enableaspectjautoproxy // 开启注解方式的aop
@slf4j
public class skyapplication {
public static void main(string[] args) {
springapplication.run(skyapplication.class, args);
log.info("server started");
}
}在这段代码中,joinpoint 是 spring aop 中的一个概念,表示连接点,即在程序执行过程中切入的某个点。signature 则是 signature 接口的实现类之一,用于表示连接点的签名信息,包括方法名、参数列表等。
具体来说,这段代码的含义是从 joinpoint 中获取连接点的签名信息,并将其强制转换为 methodsignature 类型。然后可以通过 signature 对象获取连接点(被代理方法)的详细信息,比如方法名、参数类型等。
例如,可以通过 signature.getmethod().getname() 获取连接点方法的名称,通过 signature.getparametertypes() 获取连接点方法的参数类型数组等。
需要注意的是,在实际应用中,我们使用这段代码时需要确保 joinpoint 真正代表了一个方法连接点,否则在强制转换为 methodsignature 时可能会抛出类型转换异常。

到此这篇关于springboot实现公共字段自动填充的方法步骤的文章就介绍到这了,更多相关springboot公共字段自动填充内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论