Spring Boot 3迁移:寻求org.reflections的Jakarta兼容替代方案
Spring Boot 3 替代 Reflections 扫描注解方法的方案
方案一:利用 Spring 原生类路径扫描能力
Spring 自身提供了类路径扫描工具,无需额外依赖即可实现需求,完美适配 Spring Boot 3 的 Jakarta 环境。核心思路是先扫描指定包下的控制器类,再遍历类方法筛选带 @RequestMapping 注解的方法:
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; public class RequestMappingMethodScanner { public Set<Method> getRequestMappingAnnotatedMethods(String rootPackage) { Set<Method> targetMethods = new HashSet<>(); // 创建扫描器,禁用默认过滤器(默认仅扫描@Component派生注解类) ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); // 添加过滤器,仅扫描带控制器注解的类 scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class)); scanner.addIncludeFilter(new AnnotationTypeFilter(org.springframework.stereotype.Controller.class)); // 扫描指定包下的候选组件 scanner.findCandidateComponents(rootPackage).forEach(beanDef -> { try { Class<?> clazz = Class.forName(beanDef.getBeanClassName()); // 遍历类的所有方法,筛选带@RequestMapping的方法 for (Method method : clazz.getDeclaredMethods()) { if (method.isAnnotationPresent(RequestMapping.class)) { targetMethods.add(method); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } }); return targetMethods; } }
方案二:使用活跃维护的 ClassGraph 库
ClassGraph 是一款功能强大且持续维护的类路径扫描库,完全支持 Jakarta 命名空间,API 简洁易用,适配模块化环境。
第一步:添加依赖
<dependency> <groupId>io.github.classgraph</groupId> <artifactId>classgraph</artifactId> <version>4.8.161</version> <!-- 建议使用最新稳定版 --> </dependency>
第二步:编写扫描代码
import io.github.classgraph.ClassGraph; import io.github.classgraph.MethodInfo; import io.github.classgraph.ScanResult; import org.springframework.web.bind.annotation.RequestMapping; import java.lang.reflect.Method; import java.util.Set; import java.util.stream.Collectors; public class RequestMappingMethodScanner { public Set<Method> getRequestMappingAnnotatedMethods(String rootPackage) { try (ScanResult scanResult = new ClassGraph() .enableMethodInfo() .enableAnnotationInfo() .whitelistPackages(rootPackage) .scan()) { return scanResult.getMethodInfoWithAnnotation(RequestMapping.class.getName()) .stream() .map(MethodInfo::loadClassAndGetMethod) .collect(Collectors.toSet()); } } }
这两个方案都无需复制类文件,完全适配 Spring Boot 3 的环境,其中方案一依托 Spring 原生能力,无额外依赖;方案二功能更全面,适合复杂扫描场景。
内容的提问来源于stack exchange,提问作者Ruth
相关产品推荐
相关产品推荐

