@EnableWebFlux 注解的作用是什么

Ton*_* Tc 6 spring freemarker spring-boot spring-webflux

我有一个非常简单的带有 freemarker 的 webflux 演示应用程序,它有以下文件:

1.WebFluxDemoApplication.java

@SpringBootApplication
public class WebFluxDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebFluxDemoApplication.class, args);
    }

    @Controller
    class HomeController {
        @GetMapping("/hello")
        public String hello() {
            return "index";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

2.index.ftl(位于classpath:/templates下)

<html>
    <head>
        <title>demo</title>
    </head>
    <body></body>
</html>
Run Code Online (Sandbox Code Playgroud)

3.application.yml(无需任何配置)

4.pom.xml(带spring-boot-starter-freemarkerspring-boot-starter-webflux

我可以通过http://localhost:8080/hello使用这些文件获得正常页面,但是如果我添加@EnableWebFluxWebFluxDemoApplication,则会显示错误java.lang.IllegalStateException: Could not resolve view with name 'index'.

我注意到Spring WebFlux 的官方指南指出@EnableWebFlux用于配置 freemarker。实际上它适用于模板文件,但静态资源似乎有问题。

例如,我在 下放了一个main.js文件,然后在 中classpath:/templates/js/添加,然后我得到一个错误说<script src="/js/main.js"></script>index.ftlWARN 3046 --- [ctor-http-nio-2] .a.w.r.e.DefaultErrorWebExceptionHandler : Failed to handle request [GET http://localhost:8080/js/main.js]: Response status 404 with reason "No matching handler"

更新 对于静态资源问题,我找到了一个解决方案,即添加一个RouterFunction解决静态资源的方法,如帖子所述。

Bri*_*zel 6

Spring Boot 参考文档中所述,@EnableWebFlux将告诉 Spring Boot 您希望完全控制 WebFlux 配置为此禁用所有自动配置(包括静态资源)。

@EnableWebFlux不配置 Freemarker,它实际上设置了整个 WebFlux 基础设施。在 Spring Boot 的情况下,spring-boot-starter-freemarker您只需要添加作为依赖项(并可选择通过配置属性对其进行配置)。

  • 如果是这样,我认为`@EnableWebFlux` 的名称本身就令人困惑——它没有启用 webflux 功能而是禁用所有自动配置...... (2认同)
  • EnableWebflux 是一个 Spring 框架注释,可用于从头开始设置 WebFlux 应用程序。Spring Boot 正在为您做这件事。Spring框架中没有自动配置。我知道在查看文档时事情可能会令人困惑,因此请随时通过在各自的跟踪器上创建 Spring Framework 或 Spring Boot 问题来提出更改建议。 (2认同)