如何在Spring WebFlux中以编程方式配置请求上下文属性

时间:2018-08-14 04:15:46

标签: spring spring-boot freemarker spring-webflux

根据this的注释,Spring WebFlux支持spring.freemarker.request-context-attribute,并且实际上可以正常工作。但是现在,我必须提供DelegatingWebFluxConfiguration的扩展名。根据{{​​3}}和official guide,我将DelegatingWebFluxConfiguration类扩展如下:

@Configuration
public class MyDelegatingWebFluxConfiguration extends DelegatingWebFluxConfiguration {
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.freeMarker();
    }
}

然后,除了request-context-attribute以外,其他一切似乎都还不错,因为我有以下例外:

freemarker.core.InvalidReferenceException: The following has evaluated to null or missing:
==> request  [in template "index.ftl" at line 8, column 20]

Tip: If the failing expression is known to legally refer to something that's sometimes null or missing, either specify a default value like myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing</#if>. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)??

FTL stack trace ("~" means nesting-related):
- Failed at: ${request.contextPath}  [in template "index.ftl" at line 8, column 18]

其中request的引用就是spring.freemarker.request-context-attribute的值。

因此,有人可以帮助处理此案吗?

1 个答案:

答案 0 :(得分:0)

根据Spring Framework参考,您只需要具有一个实现WebFluxConfigurer的配置类(就不应在as it will disable Spring Boot auto-configuration上使用@EnableWebFlux)。

扩展DelegatingWebFluxConfiguration与配置类上的@EnableWebFlux相同,它将告诉Spring Boot您希望完全控制WebFlux基础结构设置。

您不需要自己设置Freemarker,Spring Boot会为您完成,您只需在application.properties中进行配置即可。

使用WebFluxConfigurer应该可以在这里解决问题。