# 1.11 WebFlux Config

WebFlux Java配置声明使用带注解的控制器或功能端点来声明处理请求所必需的组件，并且它提供了用于自定义配置的API。 这意味着您不需要了解Java配置创建的基础bean。 但是，如果您想了解它们，则可以在WebFluxConfigurationSupport中查看它们，或阅读有关特殊Bean类型中的内容的更多信息。

对于配置API中没有的更高级的自定义设置，您可以通过“高级配置模式”完全控制配置。

## 1.11.1 Enabling WebFlux Config

您可以在Java配置中使用@EnableWebFlux批注，如以下示例所示：

```java
@Configuration
@EnableWebFlux
public class WebConfig {
}
```

前面的示例注册了许多Spring WebFlux基础结构Bean，并适应了classpath上可用的依赖项（对于JSON，XML等）。

## 1.11.2 WebFlux config API

在Java配置中，可以实现WebFluxConfigurer接口，如以下示例所示：

```java
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    // Implement configuration methods...

}
```

## 1.11.3 Conversion, formatting

默认情况下，将安装Number和Date类型的格式化程序，包括对@NumberFormat和@DateTimeFormat批注的支持。 如果类路径中存在Joda-Time，则还将安装对Joda-Time格式库的完全支持。

下面的示例演示如何注册自定义格式器和转换器：

```java
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // ...
    }

}
```

> 有关何时使用FormatterRegistrar实现的更多信息，请参见FormatterRegistrar SPI和FormattingConversionServiceFactoryBean。

## 1.11.4 Validation

默认情况下，如果Bean验证存在于类路径中（例如，Hibernate Validator），则LocalValidatorFactoryBean将注册为全局验证器，以与@Valid和@Controller方法参数中的Validated一起使用。

在Java配置中，您可以自定义全局Validator实例，如以下示例所示：

```java
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public Validator getValidator(); {
        // ...
    }

}
```

请注意，您还可以在本地注册Validator实现，如以下示例所示：

```java
@Controller
public class MyController {

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.addValidators(new FooValidator());
    }

}
```

如果需要在某处注入LocalValidatorFactoryBean，请创建一个bean并用@Primary进行标记，以避免与MVC配置中声明的bean发生冲突。

## 1.11.5 Content Type Resolvers

您可以配置Spring WebFlux如何根据请求为@Controller实例确定所请求的媒体类型。 默认情况下，仅选中Accept标头，但您也可以启用基于查询参数的策略。

以下示例显示如何自定义请求的内容类型解析：

```java
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void configureContentTypeResolver(RequestedContentTypeResolverBuilder builder) {
        // ...
    }
}
```

## 1.11.6 HTTP message codecs

以下示例显示如何自定义读取和写入请求和响应主体的方式：

```java
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
        // ...
    }
}
```

ServerCodecConfigurer提供了一组默认的读取器和写入器。 您可以使用它来添加更多的读取器和写入器，自定义默认的读取器或完全替换默认的读取器和写入器。

对于Jackson JSON和XML，请考虑使用Jackson2ObjectMapperBuilder，该工具使用以下属性自定义Jackson的默认属性：

* DeserializationFeature.FAIL\_ON\_UNKNOWN\_PROPERTIES被禁用。
* MapperFeature.DEFAULT\_VIEW\_INCLUSION已禁用。

如果在类路径中检测到以下知名模块，它还将自动注册以下知名模块：

* jackson-datatype-jdk7：支持Java 7类型，例如java.nio.file.Path。
* jackson-datatype-joda：支持Joda-Time类型。
* jackson-datatype-jsr310：支持Java 8日期和时间API类型。
* jackson-datatype-jdk8：支持其他Java 8类型，例如Optional。

## 1.11.7 View Resolvers

下面的示例显示如何配置视图分辨率：

```java
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        // ...
    }
}
```

ViewResolverRegistry具有与Spring Framework集成的视图技术的快捷方式。 以下示例使用FreeMarker（这也需要配置基础FreeMarker视图技术）：

```java
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {


    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.freeMarker();
    }

    // Configure Freemarker...

    @Bean
    public FreeMarkerConfigurer freeMarkerConfigurer() {
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        configurer.setTemplateLoaderPath("classpath:/templates");
        return configurer;
    }
}
```

您还可以插入任何ViewResolver实现，如以下示例所示：

```java
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {


    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        ViewResolver resolver = ... ;
        registry.viewResolver(resolver);
    }
}
```

为了支持“内容协商”并通过视图解析（HTML之外）呈现其他格式，您可以基于HttpMessageWriterView实现配置一个或多个默认视图，该实现接受spring-web中的任何可用编解码器。 以下示例显示了如何执行此操作：

```java
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {


    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.freeMarker();

        Jackson2JsonEncoder encoder = new Jackson2JsonEncoder();
        registry.defaultViews(new HttpMessageWriterView(encoder));
    }

    // ...
}
```

## 1.11.8 Static Resources

此选项提供了一种方便的方法来从基于资源的位置列表中提供静态资源。

在下一个示例中，给定一个以/ resources开头的请求，相对路径用于在类路径上查找和提供相对于/ static的静态资源。 资源的有效期为一年，以确保最大程度地利用浏览器缓存并减少浏览器发出的HTTP请求。 还评估Last-Modified头，如果存在，则返回304状态代码。 以下列表显示了示例：

```java
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
            .addResourceLocations("/public", "classpath:/static/")
            .setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS));
    }

}
```

资源处理程序还支持一系列ResourceResolver实现和ResourceTransformer实现，可用于创建用于处理优化资源的工具链。

您可以根据从内容，固定应用程序版本或其他信息计算出的MD5哈希，将VersionResourceResolver用于版本化的资源URL。 ContentVersionStrategy（MD5哈希）是一个不错的选择，但有一些值得注意的例外（例如与模块加载器一起使用的JavaScript资源）。

以下示例显示如何在Java配置中使用VersionResourceResolver：

```java
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/public/")
                .resourceChain(true)
                .addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
    }

}
```

您可以使用ResourceUrlProvider重写URL并应用完整的解析器和转换器链（例如，插入版本）。 WebFlux配置提供了ResourceUrlProvider，以便可以将其注入其他资源。

与Spring MVC不同，目前，在WebFlux中，由于没有视图技术可以利用解析器和转换器的无阻塞链，因此无法透明地重写静态资源URL。当仅提供本地资源时，解决方法是直接使用ResourceUrlProvider（例如，通过自定义元素）并进行阻止。

请注意，在同时使用EncodedResourceResolver（例如，Gzip，Brotli编码）和VersionedResourceResolver时，必须按该顺序注册它们，以确保始终基于未编码文件可靠地计算基于内容的版本。

WebJars还通过WebJarsResourceResolver支持，当org.webjars：webjars-locator-core库存在于类路径中时，WebJars将自动注册。解析程序可以重写URL以包括jar的版本，并且还可以与没有版本的传入URL进行匹配，例如，从/jquery/jquery.min.js到/jquery/1.2.0/jquery.min.js。

## 1.11.9 Path Matching

您可以自定义与路径匹配有关的选项。 有关各个选项的详细信息，请参见PathMatchConfigurer javadoc。 以下示例显示如何使用PathMatchConfigurer：

```java
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer
            .setUseCaseSensitiveMatch(true)
            .setUseTrailingSlashMatch(false)
            .addPathPrefix("/api",
                    HandlerTypePredicate.forAnnotation(RestController.class));
    }

}
```

> Spring WebFlux依赖于请求路径的解析表示形式来访问解码的路径段值，该请求路径称为RequestPath，并且已删除了分号内容（即路径或矩阵变量）。 这意味着，与Spring MVC不同，您无需指示是否解码请求路径，也无需指示是否出于路径匹配目的而删除分号内容。
>
> Spring WebFlux还不支持后缀模式匹配，这与Spring MVC不同，在Spring MVC中，我们也建议不要依赖它。

## 1.11.10 Advanced Configuration Mode

@EnableWebFlux导入DelegatingWebFluxConfiguration：

* 为WebFlux应用程序提供默认的Spring配置
* 检测并委托给WebFluxConfigurer实现以自定义该配置。

对于高级模式，您可以删除@EnableWebFlux并直接从DelegatingWebFluxConfiguration扩展而不是实现WebFluxConfigurer，如以下示例所示：

```java
@Configuration
public class WebConfig extends DelegatingWebFluxConfiguration {

    // ...

}
```

您可以将现有方法保留在Web Config中，但是现在您还可以覆盖基类中的bean声明，并且在类路径上仍然具有任意数量的其他WebMvcConfigurer实现。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.flydean.com/spring-framework-documentation5/webreactive/1.spring-webflux/1.11webflux-config.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
