简介
前段时间做接口权限管理,需要扫描项目内所有用到权限注解的方法,并获取注解里的内容。上网查阅资料后发现通过Reflections可以满足需求。
pom依赖
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.10</version>
</dependency>
具体实现
ConfigurationBuilder config = new ConfigurationBuilder();
config.filterInputsBy(new FilterBuilder().includePackage("com···controller.admin"));
config.addUrls(ClasspathHelper.forPackage("com···controller.admin"));
config.setScanners(new MethodAnnotationsScanner());
Reflections reflections = new Reflections(config);
Set<Method> methodsAnnotatedWith = reflections.getMethodsAnnotatedWith(PreAuthorize.class);
for (Method method : methodsAnnotatedWith) {
PreAuthorize annotation = method.getAnnotation(PreAuthorize.class);
String value = StringUtils.substringBetween(annotation.value(), "'", "'");
}