什么是magic-api,推荐查看官网https://www.ssssssss.org/magic-api/
目前遇到需要扩展magic-api的properties,而源码并不支持在左侧列表树接口中返回properties属性
一. 改造思路
实际上,magic-api通过org.ssssssss.magicapi.core.model.MagicEntity来表示返回对象。
通过观察,可发现构造器中未将properties进行set。
protected void simple(MagicEntity entity) {
entity.setId(this.id);
entity.setName(this.name);
entity.setGroupId(this.groupId);
entity.setCreateBy(this.createBy);
entity.setCreateTime(this.createTime);
entity.setUpdateBy(this.updateBy);
entity.setUpdateTime(this.updateTime);
entity.setLock(this.lock);
}
所以需要通过一些手段将properties注入,期望结果:
protected void simple(MagicEntity entity) {
entity.setProperties(this.properties);
entity.setId(this.id);
entity.setName(this.name);
entity.setGroupId(this.groupId);
entity.setCreateBy(this.createBy);
entity.setCreateTime(this.createTime);
entity.setUpdateBy(this.updateBy);
entity.setUpdateTime(this.updateTime);
entity.setLock(this.lock);
}
二.源码增强
新建一个MagicEnhance增强类。
@Slf4j
public class MagicEnhance {
public MagicEnhance(){
}
}
实现enhance增强方法,完整代码如下:
@Slf4j
public class MagicEnhance {
public MagicEnhance(){
}
public static void enhance() {
//初始化
ClassPool pool = ClassPool.getDefault();
//找到对应的类
CtClass ctClass;
try {
pool.importPackage("org.ssssssss.magicapi.core.model");
ctClass = pool.get("org.ssssssss.magicapi.core.model.MagicEntity");
if (ctClass.isFrozen()) {
ctClass.defrost();
}
// 找到对应的方法 通过new CtClass[]{ctClass}进行入参注入
CtMethod ctMethod = ctClass.getDeclaredMethod("simple", new CtClass[]{ctClass});
// 此处需注意,setBoday中的入参需通过$符号来指定,规则:$0表示this,$1, $2以此类推表示第1个参数,第二个参数
ctMethod.setBody("{\n" +
" $1.setProperties(this.properties);\n" +
" $1.setId(this.id);\n" +
" $1.setName(this.name);\n" +
" $1.setGroupId(this.groupId);\n" +
" $1.setCreateBy(this.createBy);\n" +
" $1.setCreateTime(this.createTime);\n" +
" $1.setUpdateBy(this.updateBy);\n" +
" $1.setUpdateTime(this.updateTime);\n" +
" $1.setLock(this.lock);\n" +
" }");
ctClass.toClass();
log.info("magic增强成功");
} catch (NotFoundException | CannotCompileException e) {
log.error("magic增强失败", e);
throw new ServiceException("magic增强失败");
}
}
}
三. 备注
使用增强之前需检查项目中有没有使用spring-boot-devtools依赖:
<!-- spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
若使用了则会在增强后导致项目启动失败,报错信息如下
LinkageError loader (instance of xxx) previously initiated loading for a different type with name...
需要将该依赖进行去除。
参考资料: