说明如何在 Boot 3.2 中配置 StaticResourceHandler 支持 MF 的 remoteEntry.js
解读
国内主流微前端方案里,Webpack Module Federation 的 remoteEntry.js 默认放在 http(s)://host/remoteEntry.js,不带任何 hash 且需要可缓存、可跨域访问。Spring Boot 3.2 默认把静态资源映射到 /static/**、/public/** 等 4 个路径,但出于安全考虑,Spring Security 6.x 会拦截所有未知路径,导致 403/404。因此,既要让静态资源 Handler 识别 remoteEntry.js,又要让 Security 放行,还要解决生产环境缓存与版本灰度问题。面试官想确认候选人是否熟悉 Boot 3.x 的 ResourceHandlerRegistry 新语义、是否理解 Security 的 requestMatchers 机制,以及是否具备线上灰度意识。
知识点
- Spring Boot 3.2 静态资源映射规则:
WebMvcAutoConfiguration自动注册 4 个类路径classpath:/META-INF/resources/,/resources/,/static/,/public/,优先级依次降低;可通过spring.web.resources.static-locations覆盖。 - ResourceHandlerRegistry 新增
setCacheControl(CacheControl)与setOptimizeLocations(true),可针对生产环境做max-age=365d, immutable,配合文件名带 hash 可彻底避免 304 回源。 - Spring Security 6.x 默认启用
authorizeHttpRequests,所有未匹配路径返回 403;放行策略需使用requestMatchers("/remoteEntry.js").permitAll(),不能用已废弃的 antMatchers。 - Module Federation 的 remoteEntry.js 不带 hash,需要自定义 VersionStrategy 或在 Nginx/网关层做灰度分发,否则上线时会出现旧版本缓存。
- Spring Boot 3.x 已全面迁移到 Jakarta EE 9,
javax.servlet包名改为jakarta.servlet,老代码直接复制会报 ClassNotFound。
答案
- 把 remoteEntry.js 放在
src/main/resources/static/mf/目录下,确保打包后位于classpath:/static/mf/remoteEntry.js。 - 新建配置类,显式注册资源映射并加缓存头:
@Configuration
@RequiredArgsConstructor
public class MfStaticConfig implements WebMvcConfigurer {
private final ResourceProperties resourceProperties; // 注入以读取配置
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 生产环境缓存一年,开发环境不缓存
CacheControl cc = Environment.current().acceptsProfiles(Profiles.of("prod"))
? CacheControl.maxAge(365, TimeUnit.DAYS).cachePublic().immutable()
: CacheControl.noCache();
registry.addResourceHandler("/mf/**") // 暴露给前端的 URL
.addResourceLocations("classpath:/static/mf/") // 实际磁盘路径
.setCacheControl(cc)
.resourceChain(true)
.addResolver(new EncodedResourceResolver()) // 支持 br、gzip
.addResolver(new PathResourceResolver());
}
}
- Spring Security 放行:
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/mf/remoteEntry.js").permitAll()
.anyRequest().authenticated()
)
.build();
}
- 本地验证:
curl -I http://localhost:8080/mf/remoteEntry.js应返回 200 且cache-control: max-age=31536000, immutable(prod 环境)。 - 上线灰度:
在 Nginx 层按 header 版本号 分发不同 remoteEntry.js,或在 网关做金丝雀路由,避免用户缓存旧入口。
拓展思考
- 如何支持多团队并行发布?
把remoteEntry.js改名为remoteEntry.{appName}.{version}.js,利用 Webpack 的 filename 模板 + Boot 的VersionResourceResolver,实现“文件名带版本、路径不变”的灰度策略。 - 若使用 React + MF 的 SSR 同构,Node 层也需要拉取 remoteEntry.js,此时需在 Boot 端开启 CORS 并设置
Access-Control-Allow-Origin: *,同时只允许 GET 方法,防止恶意上传。 - 生产环境静态资源走 CDN,可在
application-prod.yml里把spring.web.resources.static-locations指向 阿里云 OSS 挂载路径(oss://bucket/mf/),通过 Spring Cloud Alibaba OSS Starter 自动同步,实现“构建即上传”。 - Spring Boot 3.2 支持虚拟线程(Project Loom),若 MF 聚合了 10+ 子应用,可在网关层用虚拟线程并发拉取多份 remoteEntry.js,把整体冷启动时间从 3s 降到 500ms 以内,面试时可作为性能亮点抛出。