码完了增删改查,后端系统上线时,须要控制接口的访问权限。然后上千个接口的手工活。。。,那是不可能存在的。有了如下代码,读取到项目中所有的Controller,再把RequestMapping注解和日志记录注解扒出来生成权限。
public class CreateAuthProcessor implements BeanPostProcessor {
@Autowired
MenuDao menuDao;
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof RequestMappingHandlerMapping) {
RequestMappingHandlerMapping rm = (RequestMappingHandlerMapping) bean;
Map handlerMethods = rm.getHandlerMethods();
handlerMethods.forEach((k, v) -> {
doAddAuth(k, v);
});
}
return bean;
}
private void doAddAuth(RequestMappingInfo k, HandlerMethod v) {
Method method = v.getMethod();
Class> beanType = v.getBeanType();
//只取需要的的包下面的controller
if (!beanType.getName().startsWith("com.xxx")) {
return;
}
//标记在Controller类上的RequestMapping
RequestMapping parentUrl = beanType.getAnnotation(RequestMapping.class);
//MenuId 注解用于标记把该controller下的权限挂到哪个菜单下面
MenuId pmenuId = beanType.getAnnotation(MenuId.class);
//标记在方法上的RequestMapping
RequestMapping sunUrl = method.getAnnotation(RequestMapping.class);
//标记在方法上的MenuId
MenuId menuId = method.getAnnotation(MenuId.class);
//标记在方法上的日志注解
SystemLog sysLog = method.getAnnotation(SystemLog.class);
String api = "";
if (null != parentUrl && parentUrl.value().length > 0) {
String papi = parentUrl.value()[0];
if (!papi.startsWith("/")) {
papi = "/" + papi;
}
api += papi;
}
if (null != sunUrl && sunUrl.value().length > 0) {
String sapi = sunUrl.value()[0];
if (!sapi.startsWith("/")) {
sapi = "/" + sapi;
}
api += sapi;
}
api = api.replaceAll("//", "/");
if (isNull(api)) {
return;
}
api = toStar(api);
String permission = api.replaceAll("/", ":");
permission = permission.replaceAll("#", "id");
permission = "auth" + permission;
api = api.replaceAll("#", "*");
String apiName = null != sysLog ? sysLog.value() : api;
Menu menu = new Menu();
menu.setId(SnowFlake.nextKey());
if (null != menuId && isNotNull(menuId.value())) {
menu.setParentId(menuId.value());
} else if (null != pmenuId && isNotNull(pmenuId.value())) {
menu.setParentId(pmenuId.value());
} else {
menu.setParentId("123");
}
menu.setName(apiName);
menu.setSort(0);
menu.setPermission(permission);
menu.setMenuType(1);
menu.setHref(api);
menu.setDelFlag("0");
menu.setIsShow("1");
menu.setIconUrl("");
menu.setFullIconUrl("");
// menuDao.insertSelective(menu);
}
private String toStar(String api) {
if (api.indexOf("{") != -1 && api.endsWith("}")) {
return api.substring(0, api.lastIndexOf("/")) + "/#";
}
return api;
}
}
MenuId注解
@Target({ ElementType.METHOD, ElementType.FIELD,ElementType.PARAMETER ,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MenuId {
String value() default "";
}
使用示例
@RestController
@RequestMapping("/area")
@MenuId("167465851333640193")
public class AreaController extends baseController {
@RequestMapping("/list")
@SystemLog("查询地区列表")
public JsonResult findAreas(@Validated AreaQueryPo po, BindingResult br) {
return service.findAreas(po);
}
......
}
生成效果:



