有时候很懒,不喜欢去一个个 操作数据库添加,比如权限操作,就想一次性初始一下数据库,不然就很烦啊,一个个添加权限,心酸
看图,我这个权限字符串要一个个添加就很烦啊,想哭,有没有好办法呢,肯定有啊,给出方案及代码,
1.遍历包下面所有带注解的 类
2. 然后取到注解上的值
3. 插入数据库 这样是不是不需要一个个手动添加了呢。
测试类
@RestController
public class UserController{
@Autowired
private UserService userService;
@RequestMapping("user/export")
public void exportUser(HttpServletResponse httpServletResponse){
List<User> list = userService.list();
List<Map> rows = Lists.newArrayList();
list.forEach(e->{
Map row = new HashMap();
row.put("姓名",e.getName());
row.put("年龄",e.getAge());
rows.add(row);
});
ExcelUtils.exportExcel(httpServletResponse,"用户列表",rows);
}
@RequestMapping("user/import")
public Result importUser(MultipartFile file){
List<Map<String, Object>> mapList = ExcelUtils.importExcel(file);
List<User> userList = Lists.newArrayList();
mapList.forEach(e->{
String name = String.valueOf(e.get("姓名"));
Integer age = Integer.parseInt(String.valueOf(e.get("年龄")));
User user = new User();
user.setId(1);
user.setAge(age);
user.setName(name);
userList.add(user);
});
userService.saveBatch(userList);
return Result.ok();
}
@RequestMapping("user/exportTpl")
public void exportUserTpl(HttpServletResponse httpServletResponse){
List<String> hearder = Lists.newArrayList();
hearder.add("用户名");
hearder.add("年级");
ExcelUtils.exportExcelTpl(httpServletResponse,"用户模板",hearder);
}
}
@Test
public void test(){
Reflections reflections = new Reflections("com.example.demo");
Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(RestController.class);
annotated.forEach(e->{
System.out.println(e.getName());
Method[] methods = e.getMethods();
for (Method method:methods){
//System.out.println("method:" +method.getName());
RequestMapping annotation = method.getAnnotation(RequestMapping.class);
if(annotation != null){
String[] value = annotation.value();
if(value != null && value.length>=1)
System.out.println("value:" +value[0]);
}
}
});
}
结果:
elk