package com.nanri.aiimage.config; import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * 不连库、不起容器,把「Spring MVC 真正会登记的映射」原样枚举出来。 * *

为什么不用正则扫源码:{@link ApiGuardCoverageAuditor} 判的是 {@code handlerMapping.getPatternValues()}, * 类级 {@code @RequestMapping} 与方法级路径的拼接、{@code {"/a","/b"}} 多值、方法级空路径这些细节由 Spring 自己算。 * 自己抄一份正则就会和真实映射慢慢脱钩——而存量快照一旦比真实集合少一条, * 现网就变成"新增未设防端点 ⇒ 拒绝启动"的假事故(两台同时起不来=重启窗口事故重演)。 * *

做法:把控制器注册成 bean 定义 并标成懒加载,再让真实的 * {@link RequestMappingHandlerMapping#afterPropertiesSet()} 去发现它们。 * {@code preInstantiateSingletons} 跳过懒加载定义 ⇒ 控制器不被实例化(它们的构造器要 DataSource/Redis), * 登记的 HandlerMethod 只持 beanName ⇒ 不需要 DB / Redis / RocketMQ,也不需要 {@code @SpringBootTest}。 * *

这里刻意只用 {@code getMethod().getDeclaringClass()},不碰 {@code HandlerMethod#getBeanType()}—— * 后者会把 bean 解析出来,就把"不实例化"这个前提破坏了。 */ final class MappedPathProbe { static final String BASE_PACKAGE = "com.nanri.aiimage"; private MappedPathProbe() { } /** Spring 登记的全部映射(路径模式 × 处理器方法),与现网 handlerMapping.getHandlerMethods() 同口径。 */ static Map handlerMethods() { GenericApplicationContext ctx = new GenericApplicationContext(); for (Class controller : controllerClasses()) { GenericBeanDefinition def = new GenericBeanDefinition(); def.setBeanClass(controller); def.setLazyInit(true); ctx.registerBeanDefinition("probe-" + controller.getName(), def); } ctx.refresh(); RequestMappingHandlerMapping mapping = new RequestMappingHandlerMapping(); mapping.setApplicationContext(ctx); mapping.afterPropertiesSet(); Map out = new java.util.LinkedHashMap<>(); try { mapping.getHandlerMethods().forEach((info, handlerMethod) -> out.put(info, handlerMethod.getMethod().getDeclaringClass().getSimpleName() + "#" + handlerMethod.getMethod().getName())); } finally { ctx.close(); } return out; } /** @return 去重后的请求路径模式(审计器的分母单位)。 */ static Set mappedPaths() { Set paths = new LinkedHashSet<>(); handlerMethods().keySet().forEach(info -> paths.addAll(info.getPatternValues())); return paths; } /** 「路径 -> 处理器」逐条清单,供与现网 handler 数对账、也供快照生成用。 */ static List mappingLines() { List out = new ArrayList<>(); handlerMethods().forEach((info, handler) -> info.getPatternValues().forEach(p -> out.add(p + " -> " + handler))); out.sort(java.util.Comparator.naturalOrder()); return out; } /** 控制器类清单:判据与 {@code RequestMappingHandlerMapping#isHandler} 对齐。 */ static List> controllerClasses() { ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class)); scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class)); List> out = new ArrayList<>(); scanner.findCandidateComponents(BASE_PACKAGE).forEach(cd -> { String binary = cd.getBeanClassName(); // 测试夹具里的 @RestController(切片桩)不是产品端点:登记进来会让映射清单凭空多出 // 真树里没有的条目,桩与真控制器撞同一条完整路径时还会当场抛 Ambiguous mapping // (上一版切片写 GET /api/admin/users,就是把探针宿主用例打成 2 errors 的原因)。 int dollar = binary.indexOf('$'); String outermost = dollar < 0 ? binary : binary.substring(0, dollar); if (outermost.endsWith("Test") || outermost.endsWith("Tests") || outermost.endsWith("IT")) { return; } try { Class type = Class.forName(binary); boolean handler = AnnotatedElementUtils.hasAnnotation(type, Controller.class) || AnnotatedElementUtils.hasAnnotation(type, RequestMapping.class); // @ControllerAdvice / @RestControllerAdvice 不是 handler,MVC 不会为它登记映射 boolean advice = AnnotatedElementUtils.hasAnnotation(type, ControllerAdvice.class); if (handler && !advice) { out.add(type); } } catch (ClassNotFoundException e) { throw new IllegalStateException("控制器类加载失败:" + cd.getBeanClassName(), e); } }); return out; } }