我有一个小型的 Spring 启动应用程序,既可以下载又提供内容。
一些上下文:复制和服务
应用在灾难恢复盒上运行。它使用 spring 调度器通过 rest api 定期从我们的 wiki/confluence 下载一组 html 页面,然后通过嵌入式 tomcat 提供相同的.html文件。
也就是说,在主数据中心或数据库/等不可用的情况下,DR 数据中心中提供了"说明"。
一匹两招小马。只需几行代码。谢谢春天!!
使用 Spring 引导提供外部内容
我得到了如何使用自定义WebMvcConfigurer从Spring启动提供外部内容的说明[请参阅下面的代码]
但是丢失了默认的"免费"行为
添加自定义配置器"带走了"所有"我免费获得的 url 映射内容",例如自动使"/resources"目录作为 url 可供浏览器使用。 例如,"resources/styles/site.css"用作"http://localhost/styles/site.css">
我确认:当我注释掉"WebMvcConfigurer"时,Spring boot的默认"url映射到文件系统"行为按照记录的那样工作。
问题
如何扩展 WebMvcConfigurer 以保留所有"免费"的默认 Spring 启动文件到 url 映射,但添加一个外部映射,即告诉 tomcat 从这个外部目录提供内容?
谢谢!
法典
@Configuration
@EnableWebMvc
@Slf4j
/**
* Exists to allow serving up static content from the filesystem
*/
class MvcConfig implements WebMvcConfigurer {
@Autowired
AppConfig appConfig
@Override
void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/exported/**")
.addResourceLocations("file:${appConfig.outDir}/")
// I had to add this line to expose 'styles/' as a url path
registry.addResourceHandler("/styles/**")
.addResourceLocations("classpath:/public/styles/")
}
Spring MVC默认提供来自以下目录的静态内容:
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
但是WebMvcConfigurer,如问题中所述,抑制了这些默认值,这就是为什么只提供在"外部"位置找到的文件的原因。
但是,addResourceLocations
方法实际上支持字符串数组,因此您可以执行以下操作:
@Configuration
class StaticResourcesConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("file:///tmp/external-resources/",
"classpath:/static/");
}
}
现在,如果您输入/tmp/html-external.html
和src/main/resources/static/html-internal.html
,那么(假设主机/端口localhost:8080
(将同时满足两个请求:
HTTP GET: http://localhost:8080/html-external.html
HTTP GET: http://localhost:8080/html-internal.html
当然,如果你有一些控制器,它们也可以工作
更新 1
根据注释,为了将http://localhost:8080/
映射到一些预定义的index.html
:
- 添加
src/main/resources/static/index.html
- 修改
WebMvcConfigurer
,如下所示:
@Configuration
class StaticResourcesConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("file:///tmp/external-resources/",
"classpath:/static/");
registry.addResourceHandler("/")
.addResourceLocations("classpath:/static/index.html");
}
}