问题
I have a very simple webflux demo application with freemarker which has got following files:
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(located under classpath:/templates)
<html>
<head>
<title>demo</title>
</head>
<body></body>
</html>
3.application.yml(without any configuration)
4.pom.xml(with spring-boot-starter-freemarker
and spring-boot-starter-webflux
)
I can get normal page via http://localhost:8080/hello
using these files, but if I add @EnableWebFlux
to WebFluxDemoApplication
, there's an error shows java.lang.IllegalStateException: Could not resolve view with name 'index'.
I notice that the Spring WebFlux's official guide states to use @EnableWebFlux
to configure freemarker. Actually it works for template files, but there seems something wrong with static resources.
For example, I put a main.js
file under classpath:/templates/js/
, and add <script src="/js/main.js"></script>
in index.ftl
, then I get an error says 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"
UPDATE
For static resources problem, I found a solution which is to add a RouterFunction
that resolves the static resources as the post stated.
回答1:
As stated in the Spring Boot reference documentation, @EnableWebFlux will tell Spring Boot that you wish to take full control over the WebFlux configuration and disable all auto-configuration for this (including static resources).
@EnableWebFlux
doesn't configure Freemarker, it actually sets up the whole WebFlux infrastructure. In the case of Spring Boot, adding the spring-boot-starter-freemarker
as a dependency (and optionally configuring it through configuration properties) is all you need.
来源:https://stackoverflow.com/questions/51843344/what-is-the-function-of-the-enablewebflux-annotation