一、实体类定义
MenuContext:菜单上下文
@Data
public class MenuContext implements Serializable {
/**
* 系统key
*/
private String systemKey;
/**
* 项目key
*/
private String applicationKey;
/**
* 菜单集合
*/
private List<MenuVO> menus;
}
MenuVO:菜单
@Data
public class MenuVO implements Serializable {
/**
* 菜单key
*/
private String menuKey;
/**
* 菜单名称
*/
private String menuName;
/**
* 菜单路径
*/
private String path;
/**
* 排序
*/
private Integer sort;
/**
* 子菜单集合
*/
private List<MenuVO> childMenu;
/**
* 权限集合
*/
private List<AuthVO> auths;
}
AuthVO:权限
@Data
public class AuthVO implements Serializable {
/**
* 菜单key
*/
private String menuKey;
/**
* 权限key
*/
private String authKey;
/**
* 菜单名称
*/
private String authName;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AuthVO authVO = (AuthVO) o;
return Objects.equals(menuKey, authVO.menuKey) && Objects.equals(authKey, authVO.authKey);
}
@Override
public int hashCode() {
return Objects.hash(menuKey, authKey);
}
}
二、读取menu.json文件,保存为MenuContext对象
笔者想在是在SpringBoot项目初始化完毕以后读取权限配置,再保存到数据库,所以写了一个AuthorityConfig
类,实现了ApplicationRunner接口。
@Component
public class AuthorityConfig implements ApplicationContextAware, ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
// 读取菜单配置
MenuContext menuContext = buildMenu();
}
/**
* 构建菜单
*/
private static MenuContext buildMenu() throws IOException {
ClassPathResource classPathResource = new ClassPathResource("menu/menu.json");
Scanner scanner = new Scanner(classPathResource.getInputStream(), StandardCharsets.UTF_8.name());
StringBuilder menuJson = new StringBuilder();
while (scanner.hasNextLine()) {
menuJson.append(scanner.nextLine());
}
return JSON.parseObject(menuJson.toString(), MenuContext.class);
}
}
这里构建的逻辑十分的简单,就是读取了menu.json的内容,通过JSON工具包转换成了实体类