有如下 Maven 插件代码:
@Mojo(name = "generate")
public class GenerateMojo extends AbstractMojo {
@Parameter(defaultValue = "${project.build.outputDirectory}", required = true)
private File outputDirectory;
@Parameter
private File outputFile;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
Set<String> permissionCodeSet = new HashSet<>();
URL url;
try {
url = outputDirectory.toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
getLog().info(url.toString());
Reflections reflections = new Reflections(
new ConfigurationBuilder()
.addUrls(url)
.setScanners(MethodsAnnotated));
reflections.getStore().forEach((s, stringSetMap) -> {
stringSetMap.forEach((k, v) -> {
System.out.println(k);
v.forEach(System.out::println);
System.out.println();
});
});
Set<Method> resources =
reflections.get(MethodsAnnotated.with(GetMapping.class).as(Method.class));
System.out.println("resources = " + resources);
Set<Method> methodSet =
reflections.get(MethodsAnnotated.with(SaCheckPermission.class).as(Method.class));
getLog().info(methodSet.toString());
methodSet.forEach(method -> {
SaCheckPermission saCheckPermission = method.getAnnotation(SaCheckPermission.class);
List<String> values = List.of(saCheckPermission.value());
permissionCodeSet.addAll(values);
});
getLog().info(permissionCodeSet.toString());
}
}
Reflections 能够正确实例化并扫描成功,日志如下:
[INFO] Reflections took 67 ms to scan 1 urls, producing 7 keys and 79 values
尝试打印 store 内容也正确,但 methodSet 和 permissionCodeSet 均为空
尝试在使用插件的项目中运行上述代码,能够正常输出内容。
可能的问题与排查步骤:
确保
outputDirectory
指向的目录包含了含有GetMapping
和SaCheckPermission
注解的方法的已编译类文件。确认
GetMapping
和SaCheckPermission
注解的保留策略为RUNTIME
,允许在运行时通过反射获取注解信息。同时,确保类加载器能够正确加载这些类文件。检查代码中
GetMapping
和SaCheckPermission
注解是否正确应用在方法级别,并且在待扫描的类中确实存在这些注解。确认
MethodsAnnotatedScanner
正确实现了发现带有指定注解方法的功能。为进一步解决此问题,推荐在代码中增加详细的日志输出,以便精准了解
Reflections
是否在扫描过程中涵盖了期望的类和方法。同时,全面审核目标项目中注解的实际使用情况和构建流程也是至关重要的。