SpringBoot對(duì)Spring MVC都做了哪些事?(一)
環(huán)境:Springboot2.4.12
Spring MVC自動(dòng)配置
Spring Boot為Spring MVC提供了自動(dòng)配置,可以很好地與大多數(shù)應(yīng)用程序配合使用。
自動(dòng)配置在Spring默認(rèn)設(shè)置的基礎(chǔ)上添加了以下功能:
- 包含ContentNegotiatingViewResolver和BeanNameViewResolver bean。
- 支持提供靜態(tài)資源,包括對(duì)WebJars的支持(本文檔后面會(huì)講到)。
- Converter、GenericConverter和Formatterbean的自動(dòng)注冊(cè)。
- 對(duì)HttpMessageConverters的支持(本文檔后面會(huì)講到)。
- 自動(dòng)注冊(cè)MessageCodesResolver(本文檔后面將介紹)。
- 靜態(tài)index.html的支持。
- 自動(dòng)使用ConfigurableWebBindingInitializerbean(本文檔后面將介紹)。
如果你想保留那些Spring Boot MVC自定義,并做更多的MVC自定義(攔截器、格式化器、視圖控制器和其他特性),你可以添加你自己的WebMvcConfigurer類型的@Configuration類,但不需要@EnableWebMvc。
如果你想提供RequestMappingHandlerMapping、RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver的自定義實(shí)例,并且仍然保持Spring Boot MVC自定義,你可以聲明一個(gè)WebMvcRegistrations類型的bean,并使用它來(lái)提供這些組件的自定義實(shí)例。
上面這段什么意思?就是我們可以自定義一個(gè)Class實(shí)現(xiàn)WebMvcRegistrations接口實(shí)現(xiàn)自定義的上面的RequestMappingHandlerMapping等相關(guān)的類。
WebMvcRegistrations接口
public interface WebMvcRegistrations {
default RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
return null;
}
default RequestMappingHandlerAdapter getRequestMappingHandlerAdapter() {
return null;
}
default ExceptionHandlerExceptionResolver getExceptionHandlerExceptionResolver() {
return null;
}
}
自動(dòng)配置中又是如何使用(知道)我們自定義的這個(gè)WebMvcRegistrations 類呢?
proxyBeanMethods = false)(
(WebProperties.class)
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {
// 注入自定義的WebMvcRegistrations
private final WebMvcRegistrations mvcRegistrations;
public EnableWebMvcConfiguration(ObjectProvider<WebMvcRegistrations> mvcRegistrations) {
// ...
this.mvcRegistrations = mvcRegistrationsProvider.getIfUnique();
}
}
這里RequestMappingHandlerMapping 為例說(shuō)明自動(dòng)配置是如何使用自定義的。接著上面的類中,有如下方法定義。
proxyBeanMethods = false)(
(WebProperties.class)
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {
public RequestMappingHandlerAdapter requestMappingHandlerAdapter(...) {
// 調(diào)用父類的方法,這里就不進(jìn)入父類方法了,父類方法中會(huì)調(diào)用createRequestMappingHandlerAdapter
// 方法,而此方法正好被當(dāng)前類重寫了
RequestMappingHandlerAdapter adapter = super.requestMappingHandlerAdapter(contentNegotiationManager, conversionService, validator);
// ...
return adapter;
}
protected RequestMappingHandlerAdapter createRequestMappingHandlerAdapter() {
// 判斷是否存在自定義的WebMvcRegistrations接口
if (this.mvcRegistrations != null) {
RequestMappingHandlerAdapter adapter = this.mvcRegistrations.getRequestMappingHandlerAdapter();
if (adapter != null) {
return adapter;
}
}
return super.createRequestMappingHandlerAdapter();
}
}
以上就是自動(dòng)配置實(shí)現(xiàn)自定義RequestMappingHandlerMapping 等相關(guān)WebMVC核心組件的方式。
如何完全的自己控制WebMVC的配置呢?
你可以添加自己的@Configuration注釋@EnableWebMvc,或者自定義配置類 @Configuration注釋且此類是DelegatingWebMvcConfiguration的子類。
如果你想定制Spring MVC使用的ConversionService,你可以提供一個(gè)帶有addFormatters方法的WebMvcConfigurer bean。通過(guò)這個(gè)方法,你可以注冊(cè)任何你喜歡的轉(zhuǎn)換器,或者你可以委托給ApplicationConversionService上可用的靜態(tài)方法。
HttpMessageConverters
Spring MVC使用HttpMessageConverter接口來(lái)轉(zhuǎn)換HTTP請(qǐng)求和響應(yīng)。合理的默認(rèn)值是開箱即用的。例如,可以將對(duì)象自動(dòng)轉(zhuǎn)換為JSON(通過(guò)使用Jackson庫(kù))或XML(通過(guò)使用Jackson XML擴(kuò)展(如果可用),或通過(guò)使用JAXB(如果Jackson XML擴(kuò)展不可用)。缺省情況下,字符串是用UTF-8編碼的。
如果你需要添加或自定義轉(zhuǎn)換器,你可以使用Spring Boot的HttpMessageConverters類,如下所示:
proxyBeanMethods = false)(
public class MyConfiguration {
public HttpMessageConverters customConverters() {
HttpMessageConverter<?> additional = ...
HttpMessageConverter<?> another = ...
return new HttpMessageConverters(additional, another);
}
}
自動(dòng)配置又是如何使用咱們自定義的配置?
- HandlerAdapter設(shè)置HttpMessageConverter
public class WebMvcConfigurationSupport {
private List<HttpMessageConverter<?>> messageConverters;
public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
RequestMappingHandlerAdapter adapter = createRequestMappingHandlerAdapter();
// HandlerAdapter設(shè)置消息轉(zhuǎn)換器
adapter.setMessageConverters(getMessageConverters());
}
protected final List<HttpMessageConverter<?>> getMessageConverters() {
// 默認(rèn)為null
if (this.messageConverters == null) {
this.messageConverters = new ArrayList<>();
// 該方法在子類中重寫了,調(diào)用子類DelegatingWebMvcConfiguration#configureMessageConverters方法
configureMessageConverters(this.messageConverters);
if (this.messageConverters.isEmpty()) {
// 添加系統(tǒng)默認(rèn)的消息轉(zhuǎn)換器
addDefaultHttpMessageConverters(this.messageConverters);
}
extendMessageConverters(this.messageConverters);
}
return this.messageConverters;
}
}
(proxyBeanMethods = false)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
// 獲取容器中所有的自定義的WebMvcConfigurer
// 這里會(huì)有一個(gè)系統(tǒng)提供的配置類WebMvcAutoConfigurationAdapter
(required = false)
public void setConfigurers(List<WebMvcConfigurer> configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
}
}
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// 分別調(diào)用(內(nèi)部for)WebMvcConfigurer#configureMessageConverters方法
this.configurers.configureMessageConverters(converters);
}
}
系統(tǒng)提供的WebMvcConfigurer 實(shí)現(xiàn)類WebMvcAutoConfigurationAdapter。
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {
private final ObjectProvider<HttpMessageConverters> messageConvertersProvider;
public WebMvcAutoConfigurationAdapter(ObjectProvider<HttpMessageConverters> messageConvertersProvider) {
// ...
this.messageConvertersProvider = messageConvertersProvider;
// ...
}
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// 在上面的WebMvcConfigurerComposite#configureMessageConverters方法中會(huì)執(zhí)行該方法。
// 該方法先獲取有效的HttpMessageConverters
// ifAvailable方法接受一個(gè)Consumer函數(shù)式接口,將HttpMessageConverters#getConverters中的獲取到的
// HttpMessageConverter添加到當(dāng)前的List集合中
this.messageConvertersProvider.ifAvailable((customConverters) -> converters.addAll(customConverters.getConverters()));
}
}
以上就將自定義的HttpMessageConverter 添加到了容器中。
自定義JSON序列號(hào)和反序列化
如果你使用Jackson來(lái)序列化和反序列化JSON數(shù)據(jù),你可能需要編寫自己的JsonSerializer和JsonDeserializer類。自定義序列化器通常通過(guò)模塊注冊(cè)到Jackson,但Spring Boot提供了一個(gè)替代的@JsonComponent注釋,可以更容易地直接注冊(cè)Spring bean。
你可以在JsonSerializer、JsonDeserializer或KeyDeserializer實(shí)現(xiàn)中直接使用@JsonComponent注釋。你也可以在包含序列化器/反序列化器作為內(nèi)部類的類上使用它,如下所示:
public class Example {
public static class Serializer extends JsonSerializer<SomeObject> {
// ...
}
public static class Deserializer extends JsonDeserializer<SomeObject> {
// ...
}
}
ApplicationContext中的所有@JsonComponent bean都會(huì)自動(dòng)向Jackson注冊(cè)。因?yàn)锧JsonComponent是用@Component進(jìn)行元注釋的,所以通常的組件掃描規(guī)則也適用。
Spring Boot還提供了JsonObjectSerializer和JsonObjectDeserializer基類,它們?cè)谛蛄谢瘜?duì)象時(shí)提供了標(biāo)準(zhǔn)Jackson版本的有用替代方案。