我有一个非常简单的带有 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";
}
}
}
2.index.ftl (位于类路径:/模板下)
<html>
<head>
<title>demo</title>
</head>
<body></body>
</html>
3.application.yml (无需任何配置)
4.pom.xml (与
spring-boot-starter-freemarker
和 spring-boot-starter-webflux
)我可以通过
http://localhost:8080/hello
获得正常页面使用这些文件,但如果我添加 @EnableWebFlux
至 WebFluxDemoApplication
, 有错误显示 java.lang.IllegalStateException: Could not resolve view with name 'index'.
我注意到 Spring WebFlux's official guide要使用的状态
@EnableWebFlux
配置freemarker。实际上它适用于模板文件,但静态资源似乎有问题。例如,我放了一个
main.js
文件下 classpath:/templates/js/
,并添加 <script src="/js/main.js"></script>
在 index.ftl
,然后我收到一条错误消息 WARN 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
将静态资源解析为 post说。
最佳答案
如 the Spring Boot reference documentation, @EnableWebFlux
will tell Spring Boot that you wish to take full control over the WebFlux configuration 中所述并为此禁用所有自动配置(包括静态资源)。@EnableWebFlux
不配置 Freemarker,它实际上设置了整个 WebFlux 基础设施。在 Spring Boot 的情况下,添加 spring-boot-starter-freemarker
作为依赖项(并可选择通过配置属性配置它)就是您所需要的。
关于spring - @EnableWebFlux 注解的作用是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51843344/