PS:禁止拷貝形式轉(zhuǎn)載,轉(zhuǎn)載請(qǐng)以URL形式
1.參考
參考文章:# SpringMVC自定義兼容性HandlerMapping
2.簡(jiǎn)介
實(shí)現(xiàn)對(duì)靜態(tài)資源路徑的動(dòng)態(tài)修改,達(dá)到控制前端資源切換的效果。
有兩種實(shí)現(xiàn)方式
. A:基于自定義兼容性HandlerMapping
. B:更新原有映射
3.環(huán)境
- jdk11
- springboot:2.2.8.RELEASE
4.代碼
4.1 基于自定義兼容性HandlerMapping
參考文章:# SpringMVC自定義兼容性HandlerMapping
4.2 更新原有映射
原理
WebMvcConfigurationSupport 注冊(cè) 各個(gè)類型的HandlerMapping
其中注冊(cè)的 resourceHandlerMapping 負(fù)責(zé)映射靜態(tài)資源
通過修改其原有的映射信息達(dá)到控制更新

image.png
默認(rèn)映射
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String req = "/html/**";
String path = "file:C:/html/";
registry.addResourceHandler(req).addResourceLocations(path);
}
}
修改映射
public static void main(String[] args) throws Exception {
ApplicationContext app = SpringApplication.run(App.class, args);
update(app,"/html/**","file:D:/html/");
}
public static void update(ApplicationContext ctx, String url, String resource) {
SimpleUrlHandlerMapping mapping = (SimpleUrlHandlerMapping) ctx.getBean("resourceHandlerMapping");
ResourceHttpRequestHandler handler = (ResourceHttpRequestHandler) mapping.getUrlMap().get(url);
if (handler != null) {
handler.setLocationValues(List.of(resource));
handler.getLocations().clear();
handler.getResourceResolvers().clear();
try {
handler.afterPropertiesSet();
} catch (Throwable ex) {
throw new BeanInitializationException("Failed to init ResourceHttpRequestHandler", ex);
}
}
}