1. 概述

在 Web 应用中,我们常常需要提供一些静态资源,比如图片、HTML、CSS 或 JavaScript 文件。

本篇文章将介绍如何在 Spring WebFlux 项目中配置和提供静态资源。我们假设你已经使用 Spring Boot 进行了基础配置。

2. 覆盖默认配置

Spring Boot 默认会从以下几个路径加载静态资源:

  • /public
  • /static
  • /resources
  • /META-INF/resources

这些目录下的所有文件都会被映射到根路径下,例如访问 http://localhost:8080/[resource-file-name] 即可获取对应资源。

如果你希望自定义静态资源的访问路径,可以在 application.properties 文件中添加以下配置:

spring.webflux.static-path-pattern=/assets/**

此时,静态资源的访问路径就变成了 http://localhost:8080/assets/[resource-file-name]

⚠️ 注意:如果项目中使用了 @EnableWebFlux 注解,则上述配置将不会生效

3. 使用路由机制提供静态资源

除了使用默认配置外,还可以通过 WebFlux 的路由机制来提供静态资源。

3.1 提供 HTML 页面示例

比如我们要提供一个 index.html 页面,可以这样配置:

@Bean
public RouterFunction<ServerResponse> htmlRouter(
  @Value("classpath:/public/index.html") Resource html) {
    return route(GET("/"), request
      -> ok().contentType(MediaType.TEXT_HTML).syncBody(html)
    );
}

3.2 自定义路径提供图片资源

如果你想从自定义目录(如 src/main/resources/img)中提供图片资源,可以通过以下方式:

@Bean
public RouterFunction<ServerResponse> imgRouter() {
    return RouterFunctions
      .resources("/img/**", new ClassPathResource("img/"));
}

这样,访问 http://localhost:8080/img/logo.png 就会从 img 目录中加载 logo.png

4. 自定义资源目录路径

如果你希望从非默认路径(如 src/main/assets)加载静态资源,可以借助 Maven 插件和 Spring 配置实现。

4.1 使用 Maven 插件复制资源

首先,在 pom.xml 中添加 maven-resources-plugin 插件:

<plugin>
    <artifactId>maven-resources-plugin</artifactId>
    <version>3.1.0</version>
    <executions>
        <execution>
            <id>copy-resources</id>
            <phase>validate</phase>
            <goals>
                <goal>copy-resources</goal>
            </goals>
            <configuration>
                <resources>
                    <resource>
                        <directory>src/main/assets</directory>
                        <filtering>true</filtering>
                    </resource>
                </resources>
                <outputDirectory>${basedir}/target/classes/assets</outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

4.2 配置静态资源路径

然后,在 application.properties 中配置资源路径:

spring.resources.static-locations=classpath:/assets/

✅ 配置完成后,index.html 文件就可以通过 http://localhost:8080/index.html 访问了。

5. 总结

本文介绍了在 Spring WebFlux 中处理静态资源的几种方式:

  • 使用 Spring Boot 默认路径
  • 自定义静态资源访问路径
  • 通过路由机制灵活控制资源访问
  • 使用 Maven 插件配合自定义目录加载资源

这些方式可以根据项目需求灵活组合使用。

📌 示例代码可以从 GitHub 仓库 获取。


原始标题:Static Content in Spring WebFlux | Baeldung