文章目录
- java springboot Reflections工具扫描项目中带有某个注解的方法(类似@SpringBootApplication扫描各种注解)
- 简单示范
- @EnableDistributeDelayTask配置路径扫描示范(类似于@SpringBootApplication)
java springboot Reflections工具扫描项目中带有某个注解的方法(类似@SpringBootApplication扫描各种注解)
简单示范
// 要扫描的包路径
String[] scanPackages = new String[]{"cn.humorchen.delaytask"};
// 创建过滤器
FilterBuilder filterBuilder = new FilterBuilder();
for (String scanPackage : scanPackages) {
// 添加要扫描的包路径
filterBuilder.includePackage(scanPackage);
}
// 创建扫描配置
Configuration configuration = new ConfigurationBuilder().forPackages(scanPackages).filterInputsBy(filterBuilder)
.setScanners(Scanners.MethodsAnnotated);
// 使用Reflections 进行扫描
Reflections reflections = new Reflections(configuration);
// 获得加了DelayTask注解的方法
Set<Method> methodsAnnotatedWithDelayTask = reflections.getMethodsAnnotatedWith(DelayTask.class);
@EnableDistributeDelayTask配置路径扫描示范(类似于@SpringBootApplication)
public void scanProjectTask() {
// 状态切换CAS
if (INIT.compareAndSet(false, true)) {
// 要扫描的包路径
HashSet<String> scanPackageSet = new HashSet<>();
// 通过上下文拿加了启用注解的Bean
Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(EnableDistributeDelayTask.class);
for (Object bean : beansWithAnnotation.values()) {
// 获取注解
EnableDistributeDelayTask enableDistributeDelayTask = AnnotationUtil.getAnnotation(bean.getClass(), EnableDistributeDelayTask.class);
// 将注解中配置的扫描路径加入集合
if (enableDistributeDelayTask != null && enableDistributeDelayTask.scanPackages() != null && enableDistributeDelayTask.scanPackages().length > 0) {
scanPackageSet.addAll(Arrays.asList(enableDistributeDelayTask.scanPackages()));
}
// 将bean当前路径加入集合
scanPackageSet.add(bean.getClass().getPackage().getName());
}
String[] scanPackages = scanPackageSet.toArray(new String[0]);
// 构建过滤器构造器
FilterBuilder filterBuilder = new FilterBuilder();
for (String scanPackage : scanPackages) {
// 将每个包加入其中
filterBuilder.includePackage(scanPackage);
}
// 构建配置
Configuration configuration = new ConfigurationBuilder().forPackages(scanPackages).filterInputsBy(filterBuilder)
.setScanners(Scanners.MethodsAnnotated);
// 创建反射工具对象Reflections
Reflections reflections = new Reflections(configuration);
//扫描所有加了注解的方法
Set<Method> methodsAnnotatedWithDelayTask = reflections.getMethodsAnnotatedWith(DelayTask.class);
// 遍历这些方法
for (Method method : methodsAnnotatedWithDelayTask) {
// 拿到注解
DelayTask delayTaskAnnotation = AnnotationUtil.getAnnotation(method, DelayTask.class);
if (delayTaskAnnotation != null) {
// 执行加载逻辑
String taskName = delayTaskAnnotation.value();
checkTaskMethodArgsAndReturnType(taskName, method);
checkTaskNameConflict(taskName, method);
taskNameSet.add(taskName);
methodMap.put(taskName, method);
annotationMap.put(taskName, delayTaskAnnotation);
}
}
} else {
log.warn("【DistributeDelayTask】 DistributeDelayTaskServiceImpl has been initialized, skip scanProjectTask");
}
}
AnnotationUtil 见博客
https://humorchen.blog.csdn.net/article/details/139798211