栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

8.SpringMVC自动配置-Auto-configuration

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

8.SpringMVC自动配置-Auto-configuration

官方文档:https://docs.spring.io/spring-boot/docs/2.3.9.RELEASE/reference/htmlsingle/#using-boot-auto-configuration

本片文章大部分是翻译SpringBoot的使用手册中的文章,希望大家能有耐心的看文本片文章。

1、Spring MVC Auto-configuration 自动配置

备注:进入到文档直接搜索 Spring MVC Auto-configuration找到自动配置的文档介绍,打开项目双机shift 输入WebMvcAutoConfiguration查看自动配置类中的内容。

The auto-configuration adds the following features on top of Spring’s defaults:

自动配置在 Spring 默认设置的基础上增加了以下特性:

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.

    翻译:包含 ContentNegotiatingViewResolver 和 BeanNameViewResolver bean。

    自动配置ViewResolver(试图解析器:根据方法的返回值得到试图对象(View),试图对象决定如何渲染)

  • Support for serving static resources, including support for WebJars (covered later in this document)).

    翻译:支持服务静态资源,包括对 webjar 的支持。

  • Automatic registration of Converter, GenericConverter, and Formatter beans.

    翻译:转换器、 GenericConverter 和 Formatter bean 的自动注册。

    Converter :类型转换器 -接受参数时转成对象

    Formatter:格式化器:2021.10.27转成date

  • Support for HttpMessageConverters (covered later in this document).

    翻译:对 HttpMessageConverters 的支持。

  • Automatic registration of MessageCodesResolver (covered later in this document).

    翻译:MessageCodesResolver 的自动注册。

  • Static index.html support.

    翻译:静态索引支持。

  • Custom Favicon support (covered later in this document).

    翻译:自定义图标支持。

  • Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).

    翻译:自动使用 ConfigurableWebBindingInitializer bean 。

If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.

如果您希望保留 Spring Boot MVC 定制并进行更多的 MVC 定制(拦截器、格式化程序、视图控制器和其他特性) ,可以添加您自己的 webmvcrer 类型的@configuration 类,但不要添加@enablewebmvc。

If you want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations and use it to provide custom instances of those components.

如果你想提供自定义的 requestmappinghandler mapping、 requestmappinghandler adapter 或 exceptionhandlerexceptionmvc 定制,你可以声明一个类型为 WebMvcRegistrations 的 bean,并使用它来提供这些组件的自定义实例。

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc, or alternatively add your own @Configuration-annotated DelegatingWebMvcConfiguration as described in the Javadoc of @EnableWebMvc.

如果你想完全控制 Spring MVC,你可以添加你自己的@configuration 注释@enablewebmvc,或者像在@enablewebmvc 的 Javadoc 中描述的那样添加你自己的@configuration 注释 delegatingwebmvcvc 配置。

Spring MVC uses a different ConversionService to the one used to convert values from your application.properties or application.yaml file. The means that Period, Duration and DataSize converters are not available and that @DurationUnit and @DataSizeUnit annotations will be ignored.Spring MVC 使用不同的 ConversionService 来转换 application.properties 或 application.yaml 文件中的值。这意味着 Period、 Duration 和 DataSize 转换器不可用,并且@durationunit 和@datasizeunit 注释将被忽略。If you want to customize the ConversionService used by Spring MVC, you can provide a WebMvcConfigurer bean with an addFormatters method. From this method you can register any converter that you like, or you can delegate to the static methods available on ApplicationConversionService.如果希望自定义 Spring MVC 使用的 ConversionService,可以使用 addformatter 方法提供 webmvcconfigurebean。通过这个方法,您可以注册任何您喜欢的转换器,或者您可以委托给 ApplicationConversionService 上可用的静态方法。

HttpMessageConverters Http//messageconverters

Spring MVC uses the HttpMessageConverter interface to convert HTTP requests and responses. Sensible defaults are included out of the box. For example, objects can be automatically converted to JSON (by using the Jackson library) or XML (by using the Jackson XML extension, if available, or by using JAXB if the Jackson XML extension is not available). By default, strings are encoded in UTF-8.

Springmvc 使用 HttpMessageConverter 接口来转换 HTTP 请求和响应。明智的默认设置是开箱即用的。例如,对象可以自动转换为 JSON (通过使用 Jackson 库)或 XML (通过使用 Jackson XML 扩展(如果可用) ,或者通过使用 JAXB (如果 Jackson XML 扩展不可用)。默认情况下,字符串以 UTF-8编码。

If you need to add or customize converters, you can use Spring Boot’s HttpMessageConverters class, as shown in the following listing:

如果你需要添加或者定制转换器,你可以使用 Spring Boot 的 HttpMessageConverters 类,如下面的清单所示:

import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.*;

@Configuration(proxyBeanMethods = false)
public class MyConfiguration {

    @Bean
    public HttpMessageConverters customConverters() {
        HttpMessageConverter additional = ...
        HttpMessageConverter another = ...
        return new HttpMessageConverters(additional, another);
    }

}

Any HttpMessageConverter bean that is present in the context is added to the list of converters. You can also override default converters in the same way.

上下文中出现的任何 HttpMessageConverter bean 都将添加到转换器列表中。您也可以用同样的方法覆盖默认转换器。

Custom JSON Serializers and Deserializers 自定义 JSON 序列化器和反序列化器

If you use Jackson to serialize and deserialize JSON data, you might want to write your own JsonSerializer and JsonDeserializer classes. Custom serializers are usually registered with Jackson through a module, but Spring Boot provides an alternative @JsonComponent annotation that makes it easier to directly register Spring Beans.

如果使用 Jackson 对 JSON 数据进行序列化和反序列化,则可能需要编写自己的 JsonSerializer 和 JsonDeserializer 类。自定义序列化程序通常通过一个模块向 Jackson 注册,但 Spring Boot 提供了一个替代的@jsoncomponent 注释,使得直接注册 Spring Beans 变得更加容易。

You can use the @JsonComponent annotation directly on JsonSerializer, JsonDeserializer or KeyDeserializer implementations. You can also use it on classes that contain serializers/deserializers as inner classes, as shown in the following example:

您可以直接在 JsonSerializer、 JsonDeserializer 或 KeyDeserializer 实现上使用@jsoncomponent 注释。也可以在包含序列化器/反序列化器作为内部类的类上使用它,如下面的示例所示:

import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import org.springframework.boot.jackson.*;

@JsonComponent
public class Example {

    public static class Serializer extends JsonSerializer {
        // ...
    }

    public static class Deserializer extends JsonDeserializer {
        // ...
    }

}

All @JsonComponent beans in the ApplicationContext are automatically registered with Jackson. Because @JsonComponent is meta-annotated with @Component, the usual component-scanning rules apply.

ApplicationContext 中的所有@jsoncomponent bean 都会自动向 Jackson 注册。因为@jsoncomponent 使用@component 进行了元注释,所以应用了通常的组件扫描规则。

Spring Boot also provides JsonObjectSerializer and JsonObjectDeserializer base classes that provide useful alternatives to the standard Jackson versions when serializing objects. See JsonObjectSerializer and JsonObjectDeserializer in the Javadoc for details.

Spring Boot 还提供了 JsonObjectSerializer 和 JsonObjectDeserializer 基类,它们在序列化对象时为标准 Jackson 版本提供了有用的替代方法。有关详细信息,请参阅 Javadoc 中的 JsonObjectSerializer 和 JsonObjectDeserializer。

1.1MessageCodesResolver

Spring MVC has a strategy for generating error codes for rendering error messages from binding errors: MessageCodesResolver. If you set the spring.mvc.message-codes-resolver-format property PREFIX_ERROR_CODE or POSTFIX_ERROR_CODE, Spring Boot creates one for you (see the enumeration in DefaultMessageCodesResolver.Format).

Springmvc 有一个用于生成错误代码的策略,用于从绑定错误中呈现错误消息: MessageCodesResolver。如果您设置了 Spring.mvc.message-codes-resolver-format 属性 PREFIX _ error _ code 或 POSTFIX _ error _ code,Spring Boot 将为您创建一个属性(参见 DefaultMessageCodesResolver 中的枚举)。格式)。

1.2Static Content 静态内容

By default, Spring Boot serves static content from a directory called /static (or /public or /resources or /meta-INF/resources) in the classpath or from the root of the ServletContext. It uses the ResourceHttpRequestHandler from Spring MVC so that you can modify that behavior by adding your own WebMvcConfigurer and overriding the addResourceHandlers method.

默认情况下,Spring Boot 从类路径中的/static (或/public 或/resources 或/meta-INF/resources)目录或 ServletContext 的根目录提供静态内容。它使用 Spring MVC 中的 ResourceHttpRequestHandler,因此您可以通过添加自己的 webmvcconfigureer 和重写 resourcehandlers 方法来修改该行为。

In a stand-alone web application, the default servlet from the container is also enabled and acts as a fallback, serving content from the root of the ServletContext if Spring decides not to handle it. Most of the time, this does not happen (unless you modify the default MVC configuration), because Spring can always handle requests through the DispatcherServlet.

By default, resources are mapped on /**, but you can tune that with the spring.mvc.static-path-pattern property. For instance, relocating all resources to /resources/** can be achieved as follows:

默认情况下,资源映射在/* * 上,但是可以使用 spring.mvc.static-path-pattern 属性对其进行优化。例如,将所有资源转移到/resources/* * 可以做到以下几点:

spring.mvc.static-path-pattern=/resources/**

You can also customize the static resource locations by using the spring.resources.static-locations property (replacing the default values with a list of directory locations). The root Servlet context path, "/", is automatically added as a location as well.

还可以使用 spring.resources.static-locations 属性(用目录位置列表替换默认值)自定义静态资源位置。根 Servlet 上下文路径“/”也会自动作为位置添加。

In addition to the “standard” static resource locations mentioned earlier, a special case is made for Webjars content. Any resources with a path in /webjars/** are served from jar files if they are packaged in the Webjars format.

除了前面提到的“标准”静态资源位置之外,还为 Webjars 内容制作了一个特例。任何路径在/webjar/* * 中的资源如果以 Webjars 格式打包,都可以从 jar 文件中获得。

Do not use the 不要使用src/main/webapp directory if your application is packaged as a jar. Although this directory is a common standard, it works 尽管这个目录是一个通用的标准,但是它是可以工作的only 只 with war packaging, and it is silently ignored by most build tools if you generate a jar. 如果你生成一个 jar,大多数构建工具都会默默地忽略它

Spring Boot also supports the advanced resource handling features provided by Spring MVC, allowing use cases such as cache-busting static resources or using version agnostic URLs for Webjars.

Spring Boot 还支持 Spring MVC 提供的高级资源处理特性,允许使用例如缓存破坏静态资源或为 Webjars 使用版本不可知的 url。

To use version agnostic URLs for Webjars, add the webjars-locator-core dependency. Then declare your Webjar. Using jQuery as an example, adding "/webjars/jquery/jquery.min.js" results in "/webjars/jquery/x.y.z/jquery.min.js" where x.y.z is the Webjar version.

若要为 Webjars 使用版本不可知的 url,请添加 Webjars-locator-core 依赖项。然后声明你的 Webjar。以 jQuery 为例,添加”/webjars/jQuery/jQuery.min.js”会导致”/webjars/jQuery/x.y.z/jQuery.min.js”,其中 x.y.z 是 Webjar 版本。

If you use JBoss, you need to declare the webjars-locator-jboss-vfs dependency instead of the 依赖性而不是webjars-locator-core. Otherwise, all Webjars resolve as a 。否则,所有 webjar 将解析为404.

To use cache busting, the following configuration configures a cache busting solution for all static resources, effectively adding a content hash, such as

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/351978.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号