【Spring Boot】(13)、Spring Boot自動設定SpringMVC

來源:互聯網
上載者:User
1、SpringMVC自動設定官方文檔

Spring Boot官方文檔:Spring Boot中Springmvc配置文檔


2、Spring MVC auto-configuration

Spring Boot 提供了大多數SpringMVC應用常用的自動設定項。

以下是Spring Boot對SpringMVC的預設配置(來自官網,自行翻譯): 自動設定了 ContentNegotiatingViewResolver 和 BeanNameViewResolver 的Beans.

給容器自訂添加一個視圖解析器,該ContentNegotiatingViewResolver 的bean會自動組合進來。

自動設定了ViewResolver:ContentNegotiatingViewResolver是組合了所有的視圖解析器

public class WebMvcAutoConfiguration {    //other code...        @Bean    @ConditionalOnBean(ViewResolver.class)    @ConditionalOnMissingBean(name = "viewResolver", value = ContentNegotiatingViewResolver.class)    public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {        ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();        resolver.setContentNegotiationManager(            beanFactory.getBean(ContentNegotiationManager.class));        // ContentNegotiatingViewResolver uses all the other view resolvers to locate        // a view so it should have a high precedence        resolver.setOrder(Ordered.HIGHEST_PRECEDENCE);        return resolver;    }}

其中ContentNegotiatintViewResolver類實現ViewResoler介面:

public class ContentNegotiatingViewResolver extends WebApplicationObjectSupportimplements ViewResolver, Ordered, InitializingBean {//other code...@Overridepublic View resolveViewName(String viewName, Locale locale) throws Exception {RequestAttributes attrs = RequestContextHolder.getRequestAttributes();Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");//擷取所有的MediaType,例如application/json,text/html等等。。。List<MediaType> requestedMediaTypes = getMediaTypes(((ServletRequestAttributes) attrs).getRequest());if (requestedMediaTypes != null) {//擷取所有的視圖List<View> candidateViews = getCandidateViews(viewName, locale, requestedMediaTypes);//根據請求擷取最適合的視圖View bestView = getBestView(candidateViews, requestedMediaTypes, attrs);if (bestView != null) {return bestView;}}//other code...}private List<View> getCandidateViews(String viewName, Locale locale, List<MediaType> requestedMediaTypes)throws Exception {List<View> candidateViews = new ArrayList<View>();for (ViewResolver viewResolver : this.viewResolvers) {View view = viewResolver.resolveViewName(viewName, locale);if (view != null) {candidateViews.add(view);}for (MediaType requestedMediaType : requestedMediaTypes) {List<String> extensions = this.contentNegotiationManager.resolveFileExtensions(requestedMediaType);for (String extension : extensions) {String viewNameWithExtension = viewName + '.' + extension;view = viewResolver.resolveViewName(viewNameWithExtension, locale);if (view != null) {candidateViews.add(view);}}}}//other code...return candidateViews;}}
支援靜態資源檔案夾和webjars 靜態首頁的訪問。 自訂favicon表徵圖 自動註冊了 Converter, GenericConverter, Formatter Beans.

Converter:轉換器,用於類型轉換

Formatter:格式化器

@Bean//如果配置了spring.mvc.date-format,則自動註冊Formatter<Date>的Bean@ConditionalOnProperty(prefix = "spring.mvc", name = "date-format")public Formatter<Date> dateFormatter() {    return new DateFormatter(this.mvcProperties.getDateFormat());}

        自動添加的格式化轉換器,只需添加到容器中即可。 支援HttpMessageConverters 訊息轉換器。

HttpMessageConverter:SpringMVC用來轉換Http請求和響應的

HttpMessageConverters 是從容器中擷取的所有的HttpMessageConverter,如果需要給容器中添加HttpMessageConverter,只需要將自訂的組件註冊在容器中即可。 自動設定 MessageCodesResolver 用於錯誤碼的建置規則。

PREFIX_ERROR_CODE: error_code + "." + object name + "." + field

POSTFIX_ERROR_CODE:object name + "." + field + "." + error_code 自動使用 ConfigurableWebBindingInitializerBean。

可以自訂配置一個ConfigurableWebBindingInitializer來替換預設的,需要添加到容器中。

初始化WebDataBinder:用於將請求資料繫結到資料模型等。

包org.springframework.boot.autoconfigure.web是web的所有自動設定情境。

    來自官網:   

    If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type WebMvcConfigurerAdapter, but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver you can declare a WebMvcRegistrationsAdapter instance providing such components.

    If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.
3、擴充SpringMVC

編寫一個配置類,是WebMvcConfigurerAdapter類的子類,但是不能標註@EnableWebMvc註解。

這樣既保留了所有的自動設定,也能使用自訂的擴充配置。

//使用WebMvcConfigurerAdapter可以來擴充SpringMVC的功能@Configurationpublic class MyMvcConfig extends WebMvcConfigurerAdapter{@Overridepublic void addViewControllers(ViewControllerRegistry registry) {//super.addViewControllers(registry);        //瀏覽器發送/cay請求,會直接跳到success頁面。registry.addViewController("/cay").setViewName("success");}}

原理: 1)、WebMvcAutoConfiguration是SpringMVC的自動設定類,在內部維護了一個內部類WebMvcAutoConfigurationAdapter,該類又繼承自WebMvcConfigurerAdapter,看定義:

@Configuration@Import(EnableWebMvcConfiguration.class)@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })public static class WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter {}

    而WebMvcConfigurerAdapter又實現了WebMvcConfigurer介面:

public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {}
    所以自訂的配置類(此例為MyMvcConfig)是個 WebMvcConfigurer 介面的實作類別。


     2)、在做WebMvcAutoConfigurationAdapter自動設定時會匯入@Import(EnableWebMvcConfiguration.class)

@Configurationpublic static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {}

父類:

@Configurationpublic class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();//從容器中擷取所有的WebMvcConfigurer@Autowired(required = false)public void setConfigurers(List<WebMvcConfigurer> configurers) {if (!CollectionUtils.isEmpty(configurers)) {this.configurers.addWebMvcConfigurers(configurers);}}}
     3)、容器中所有的WebMvcConfigurer都會一起起作用。
class WebMvcConfigurerComposite implements WebMvcConfigurer {private final List<WebMvcConfigurer> delegates = new ArrayList<WebMvcConfigurer>();public void addWebMvcConfigurers(List<WebMvcConfigurer> configurers) {if (!CollectionUtils.isEmpty(configurers)) {this.delegates.addAll(configurers);}}        @Overridepublic void addFormatters(FormatterRegistry registry) {for (WebMvcConfigurer delegate : this.delegates) {delegate.addFormatters(registry);}}@Overridepublic void addInterceptors(InterceptorRegistry registry) {for (WebMvcConfigurer delegate : this.delegates) {delegate.addInterceptors(registry);}}        @Overridepublic void addViewControllers(ViewControllerRegistry registry) {for (WebMvcConfigurer delegate : this.delegates) {delegate.addViewControllers(registry);}}        //other code...}

從源碼中可以看到,從容器中擷取的所有WebMvcConfigurer對象都會被調用對應的配置方法。
        4)、最後可以結合第2點和第3點看出,自訂的配置類也會被調用。
總結:SpringMVC的自動設定和自訂的擴充配置都會起作用。

4、全面接管SpringMVC

    在配置類上使用@EnableWebMvc註解,這樣Spring Boot對SpringMVC的自動設定就失效了,所有都需要自訂配置。

原理:為什麼使用了@EnableWebMvc後自動設定就失效了?

        1)、EnableWebMvc註解的定義

@Import(DelegatingWebMvcConfiguration.class)public @interface EnableWebMvc {}

          2)、匯入了DelegatingWebMvcConfiguration組件配置

@Configurationpublic class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {}

          3)、查看WebMvcAutoConfiguration自動設定類的簽名

@Configuration@ConditionalOnWebApplication@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,WebMvcConfigurerAdapter.class })//如果容器中沒有該組件的時候,這個自動設定類就自動生效。@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,ValidationAutoConfiguration.class })public class WebMvcAutoConfiguration {}

           4)、@EnableWebMvc將WebMvcConfigurationSupport組件匯入進來了,導致Spring Boot對SpringMVC的自動設定失效,即WebMvcAutoonfiguration配置類未註冊成功。


5、修改SpringBoot的預設配置

模式:

1)、Spring Boot在自動設定很多組件的時候,會先檢查容器中是否有使用者自訂配置的Bean或者組件。如果有,就使用使用者自訂的;如果沒有,Spring Boot才自動設定;如果有些組件可以有多個,使用者可以自訂添加組件,並加入到容器中,這樣Spring Boot會自動將使用者配置的和預設的組合起來。

2)、在Spring Boot中會有很多的Configurer協助使用者進行擴充配置。


====================打個廣告,歡迎關注====================

QQ:
412425870</

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.