springboot的Web开发-Web相关配置

一:Spring Boot提供自动配置

       通过查看WebMvcAutoConfiguration及WebMvcProperties的源码,可以发现Spring Boot为我们提供了如下的自动配置。

 1,自动配置的ViewResolver

1)ContentNegotiatingViewResolver

    这是Spring MVC提供的一个特殊的ViewResolver,ContentNegotiatingViewResolver不是自己处理View,而是代理给不同的ViewResolver来处理不同的View,所以它有最高的优先级。

2)BeanNameViewResolver

    在控制器(@Controller)中的一个方法的返回值的字符串(视图名)会根据 BeanNameViewResolver去查找Bean的名称为返回字符串的View来渲染视图,下面举个例子

     定义BeanNameViewResolver的Bean

 

[java]  view plain  copy
 
  1. @Bean  
  2.     public BeanNameViewResolver beanNameViewResolver(){  
  3.         BeanNameViewResolver resolver= new BeanNameViewResolver();  
  4.         return resolver  
  5.     }  



 

   定义一个View的Bean,名称为jsonView

 

[java]  view plain  copy
 
  1. @Bean  
  2.     public MappingJackson2JsonView jsonView(){  
  3.         MappingJackson2JsonView jsonView = new MappingJackson2JsonView();  
  4.         return jsonView;  
  5.     }  


     在控制器中,返回值为字符串jsonView,它会找Bean的名称为jsonView的视图来渲染:

 

 

[java]  view plain  copy
 
  1. @RequestMapping(value = "json",produces = {MediaType.APPLICATION_JSON_VALUE})  
  2.     public String json(Model model){  
  3.         Person single = new Person("aa",11);  
  4.         model.addAttribute("single",single);  
  5.         return "jsonView";  
  6.     }  


3)InternalResourceViewResolver

 

    这是一个常用的ViewResolver,主要通过设置前缀,后缀,以及控制器中方法来返回视图名的字符串,以得到实际页面,Spring Boot的源码如下:

 

[java]  view plain  copy
 
  1. @Bean  
  2.         @ConditionalOnMissingBean  
  3.         public InternalResourceViewResolver defaultViewResolver() {  
  4.             InternalResourceViewResolver resolver = new InternalResourceViewResolver();  
  5.             resolver.setPrefix(this.mvcProperties.getView().getPrefix());  
  6.             resolver.setSuffix(this.mvcProperties.getView().getSuffix());  
  7.             return resolver;  
  8.         }  


下面是WebMvcAutoConfiguration的源代码:

 

 

[java]  view plain  copy
 
  1. //  
  2. // Source code recreated from a .class file by IntelliJ IDEA  
  3. // (powered by Fernflower decompiler)  
  4. //  
  5.   
  6. package org.springframework.boot.autoconfigure.web;  
  7.   
  8. import java.util.Collection;  
  9. import java.util.Collections;  
  10. import java.util.Date;  
  11. import java.util.Iterator;  
  12. import java.util.List;  
  13. import java.util.ListIterator;  
  14. import java.util.Map;  
  15. import java.util.Map.Entry;  
  16. import javax.servlet.Servlet;  
  17. import javax.servlet.http.HttpServletRequest;  
  18. import org.apache.commons.logging.Log;  
  19. import org.apache.commons.logging.LogFactory;  
  20. import org.springframework.beans.factory.BeanFactory;  
  21. import org.springframework.beans.factory.ListableBeanFactory;  
  22. import org.springframework.beans.factory.NoSuchBeanDefinitionException;  
  23. import org.springframework.beans.factory.ObjectProvider;  
  24. import org.springframework.beans.factory.annotation.Autowired;  
  25. import org.springframework.boot.autoconfigure.AutoConfigureAfter;  
  26. import org.springframework.boot.autoconfigure.AutoConfigureOrder;  
  27. import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;  
  28. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;  
  29. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;  
  30. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;  
  31. import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;  
  32. import org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration;  
  33. import org.springframework.boot.autoconfigure.web.ResourceProperties.Chain;  
  34. import org.springframework.boot.autoconfigure.web.ResourceProperties.Strategy;  
  35. import org.springframework.boot.context.properties.EnableConfigurationProperties;  
  36. import org.springframework.boot.web.filter.OrderedHiddenHttpMethodFilter;  
  37. import org.springframework.boot.web.filter.OrderedHttpPutFormContentFilter;  
  38. import org.springframework.boot.web.filter.OrderedRequestContextFilter;  
  39. import org.springframework.context.annotation.Bean;  
  40. import org.springframework.context.annotation.Configuration;  
  41. import org.springframework.context.annotation.Import;  
  42. import org.springframework.context.annotation.Lazy;  
  43. import org.springframework.context.annotation.Primary;  
  44. import org.springframework.core.convert.converter.Converter;  
  45. import org.springframework.core.convert.converter.GenericConverter;  
  46. import org.springframework.core.io.Resource;  
  47. import org.springframework.format.Formatter;  
  48. import org.springframework.format.FormatterRegistry;  
  49. import org.springframework.format.datetime.DateFormatter;  
  50. import org.springframework.http.MediaType;  
  51. import org.springframework.http.converter.HttpMessageConverter;  
  52. import org.springframework.util.ClassUtils;  
  53. import org.springframework.util.StringUtils;  
  54. import org.springframework.validation.DefaultMessageCodesResolver;  
  55. import org.springframework.validation.MessageCodesResolver;  
  56. import org.springframework.validation.Validator;  
  57. import org.springframework.web.HttpMediaTypeNotAcceptableException;  
  58. import org.springframework.web.accept.ContentNegotiationManager;  
  59. import org.springframework.web.accept.ContentNegotiationStrategy;  
  60. import org.springframework.web.accept.PathExtensionContentNegotiationStrategy;  
  61. import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;  
  62. import org.springframework.web.context.request.NativeWebRequest;  
  63. import org.springframework.web.context.request.RequestContextListener;  
  64. import org.springframework.web.filter.HiddenHttpMethodFilter;  
  65. import org.springframework.web.filter.HttpPutFormContentFilter;  
  66. import org.springframework.web.filter.RequestContextFilter;  
  67. import org.springframework.web.servlet.DispatcherServlet;  
  68. import org.springframework.web.servlet.HandlerExceptionResolver;  
  69. import org.springframework.web.servlet.LocaleResolver;  
  70. import org.springframework.web.servlet.View;  
  71. import org.springframework.web.servlet.ViewResolver;  
  72. import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;  
  73. import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;  
  74. import org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration;  
  75. import org.springframework.web.servlet.config.annotation.ResourceChainRegistration;  
  76. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;  
  77. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;  
  78. import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;  
  79. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;  
  80. import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;  
  81. import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping;  
  82. import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;  
  83. import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;  
  84. import org.springframework.web.servlet.i18n.FixedLocaleResolver;  
  85. import org.springframework.web.servlet.mvc.ParameterizableViewController;  
  86. import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;  
  87. import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;  
  88. import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;  
  89. import org.springframework.web.servlet.resource.AppCacheManifestTransformer;  
  90. import org.springframework.web.servlet.resource.GzipResourceResolver;  
  91. import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;  
  92. import org.springframework.web.servlet.resource.ResourceResolver;  
  93. import org.springframework.web.servlet.resource.VersionResourceResolver;  
  94. import org.springframework.web.servlet.view.BeanNameViewResolver;  
  95. import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;  
  96. import org.springframework.web.servlet.view.InternalResourceViewResolver;  
  97.   
  98. @Configuration  
  99. @ConditionalOnWebApplication  
  100. @ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurerAdapter.class})  
  101. @ConditionalOnMissingBean({WebMvcConfigurationSupport.class})  
  102. @AutoConfigureOrder(-2147483638)  
  103. @AutoConfigureAfter({DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class})  
  104. public class WebMvcAutoConfiguration {  
  105.     public static final String DEFAULT_PREFIX = "";  
  106.     public static final String DEFAULT_SUFFIX = "";  
  107.   
  108.     public WebMvcAutoConfiguration() {  
  109.     }  
  110.   
  111.     @Bean  
  112.     @ConditionalOnMissingBean({HiddenHttpMethodFilter.class})  
  113.     public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {  
  114.         return new OrderedHiddenHttpMethodFilter();  
  115.     }  
  116.   
  117.     @Bean  
  118.     @ConditionalOnMissingBean({HttpPutFormContentFilter.class})  
  119.     @ConditionalOnProperty(  
  120.         prefix = "spring.mvc.formcontent.putfilter",  
  121.         name = {"enabled"},  
  122.         matchIfMissing = true  
  123.     )  
  124.     public OrderedHttpPutFormContentFilter httpPutFormContentFilter() {  
  125.         return new OrderedHttpPutFormContentFilter();  
  126.     }  
  127.   
  128.     static class OptionalPathExtensionContentNegotiationStrategy implements ContentNegotiationStrategy {  
  129.         private static final String SKIP_ATTRIBUTE = PathExtensionContentNegotiationStrategy.class.getName() + ".SKIP";  
  130.         private final ContentNegotiationStrategy delegate;  
  131.   
  132.         OptionalPathExtensionContentNegotiationStrategy(ContentNegotiationStrategy delegate) {  
  133.             this.delegate = delegate;  
  134.         }  
  135.   
  136.         public List<MediaType> resolveMediaTypes(NativeWebRequest webRequest) throws HttpMediaTypeNotAcceptableException {  
  137.             Object skip = webRequest.getAttribute(SKIP_ATTRIBUTE, 0);  
  138.             return skip != null && Boolean.parseBoolean(skip.toString()) ? Collections.emptyList() : this.delegate.resolveMediaTypes(webRequest);  
  139.         }  
  140.     }  
  141.   
  142.     static final class WelcomePageHandlerMapping extends AbstractUrlHandlerMapping {  
  143.         private static final Log logger = LogFactory.getLog(WebMvcAutoConfiguration.WelcomePageHandlerMapping.class);  
  144.   
  145.         private WelcomePageHandlerMapping(Resource welcomePage, String staticPathPattern) {  
  146.             if (welcomePage != null && "/**".equals(staticPathPattern)) {  
  147.                 logger.info("Adding welcome page: " + welcomePage);  
  148.                 ParameterizableViewController controller = new ParameterizableViewController();  
  149.                 controller.setViewName("forward:index.html");  
  150.                 this.setRootHandler(controller);  
  151.                 this.setOrder(0);  
  152.             }  
  153.   
  154.         }  
  155.   
  156.         public Object getHandlerInternal(HttpServletRequest request) throws Exception {  
  157.             Iterator var2 = this.getAcceptedMediaTypes(request).iterator();  
  158.   
  159.             MediaType mediaType;  
  160.             do {  
  161.                 if (!var2.hasNext()) {  
  162.                     return null;  
  163.                 }  
  164.   
  165.                 mediaType = (MediaType)var2.next();  
  166.             } while(!mediaType.includes(MediaType.TEXT_HTML));  
  167.   
  168.             return super.getHandlerInternal(request);  
  169.         }  
  170.   
  171.         private List<MediaType> getAcceptedMediaTypes(HttpServletRequest request) {  
  172.             String acceptHeader = request.getHeader("Accept");  
  173.             return MediaType.parseMediaTypes(StringUtils.hasText(acceptHeader) ? acceptHeader : "*/*");  
  174.         }  
  175.     }  
  176.   
  177.     private static class ResourceChainResourceHandlerRegistrationCustomizer implements WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer {  
  178.         @Autowired  
  179.         private ResourceProperties resourceProperties;  
  180.   
  181.         private ResourceChainResourceHandlerRegistrationCustomizer() {  
  182.             this.resourceProperties = new ResourceProperties();  
  183.         }  
  184.   
  185.         public void customize(ResourceHandlerRegistration registration) {  
  186.             Chain properties = this.resourceProperties.getChain();  
  187.             this.configureResourceChain(properties, registration.resourceChain(properties.isCache()));  
  188.         }  
  189.   
  190.         private void configureResourceChain(Chain properties, ResourceChainRegistration chain) {  
  191.             Strategy strategy = properties.getStrategy();  
  192.             if (strategy.getFixed().isEnabled() || strategy.getContent().isEnabled()) {  
  193.                 chain.addResolver(this.getVersionResourceResolver(strategy));  
  194.             }  
  195.   
  196.             if (properties.isGzipped()) {  
  197.                 chain.addResolver(new GzipResourceResolver());  
  198.             }  
  199.   
  200.             if (properties.isHtmlApplicationCache()) {  
  201.                 chain.addTransformer(new AppCacheManifestTransformer());  
  202.             }  
  203.   
  204.         }  
  205.   
  206.         private ResourceResolver getVersionResourceResolver(Strategy properties) {  
  207.             VersionResourceResolver resolver = new VersionResourceResolver();  
  208.             if (properties.getFixed().isEnabled()) {  
  209.                 String version = properties.getFixed().getVersion();  
  210.                 String[] paths = properties.getFixed().getPaths();  
  211.                 resolver.addFixedVersionStrategy(version, paths);  
  212.             }  
  213.   
  214.             if (properties.getContent().isEnabled()) {  
  215.                 String[] paths = properties.getContent().getPaths();  
  216.                 resolver.addContentVersionStrategy(paths);  
  217.             }  
  218.   
  219.             return resolver;  
  220.         }  
  221.     }  
  222.   
  223.     interface ResourceHandlerRegistrationCustomizer {  
  224.         void customize(ResourceHandlerRegistration var1);  
  225.     }  
  226.   
  227.     @Configuration  
  228.     @ConditionalOnEnabledResourceChain  
  229.     static class ResourceChainCustomizerConfiguration {  
  230.         ResourceChainCustomizerConfiguration() {  
  231.         }  
  232.   
  233.         @Bean  
  234.         public WebMvcAutoConfiguration.ResourceChainResourceHandlerRegistrationCustomizer resourceHandlerRegistrationCustomizer() {  
  235.             return new WebMvcAutoConfiguration.ResourceChainResourceHandlerRegistrationCustomizer();  
  236.         }  
  237.     }  
  238.   
  239.     @Configuration  
  240.     public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {  
  241.         private final WebMvcProperties mvcProperties;  
  242.         private final ListableBeanFactory beanFactory;  
  243.         private final WebMvcRegistrations mvcRegistrations;  
  244.   
  245.         public EnableWebMvcConfiguration(ObjectProvider<WebMvcProperties> mvcPropertiesProvider, ObjectProvider<WebMvcRegistrations> mvcRegistrationsProvider, ListableBeanFactory beanFactory) {  
  246.             this.mvcProperties = (WebMvcProperties)mvcPropertiesProvider.getIfAvailable();  
  247.             this.mvcRegistrations = (WebMvcRegistrations)mvcRegistrationsProvider.getIfUnique();  
  248.             this.beanFactory = beanFactory;  
  249.         }  
  250.   
  251.         @Bean  
  252.         public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {  
  253.             RequestMappingHandlerAdapter adapter = super.requestMappingHandlerAdapter();  
  254.             adapter.setIgnoreDefaultModelOnRedirect(this.mvcProperties == null ? true : this.mvcProperties.isIgnoreDefaultModelOnRedirect());  
  255.             return adapter;  
  256.         }  
  257.   
  258.         protected RequestMappingHandlerAdapter createRequestMappingHandlerAdapter() {  
  259.             return this.mvcRegistrations != null && this.mvcRegistrations.getRequestMappingHandlerAdapter() != null ? this.mvcRegistrations.getRequestMappingHandlerAdapter() : super.createRequestMappingHandlerAdapter();  
  260.         }  
  261.   
  262.         @Bean  
  263.         @Primary  
  264.         public RequestMappingHandlerMapping requestMappingHandlerMapping() {  
  265.             return super.requestMappingHandlerMapping();  
  266.         }  
  267.   
  268.         @Bean  
  269.         public Validator mvcValidator() {  
  270.             return !ClassUtils.isPresent("javax.validation.Validator", this.getClass().getClassLoader()) ? super.mvcValidator() : WebMvcValidator.get(this.getApplicationContext(), this.getValidator());  
  271.         }  
  272.   
  273.         protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() {  
  274.             return this.mvcRegistrations != null && this.mvcRegistrations.getRequestMappingHandlerMapping() != null ? this.mvcRegistrations.getRequestMappingHandlerMapping() : super.createRequestMappingHandlerMapping();  
  275.         }  
  276.   
  277.         protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer() {  
  278.             try {  
  279.                 return (ConfigurableWebBindingInitializer)this.beanFactory.getBean(ConfigurableWebBindingInitializer.class);  
  280.             } catch (NoSuchBeanDefinitionException var2) {  
  281.                 return super.getConfigurableWebBindingInitializer();  
  282.             }  
  283.         }  
  284.   
  285.         protected ExceptionHandlerExceptionResolver createExceptionHandlerExceptionResolver() {  
  286.             return this.mvcRegistrations != null && this.mvcRegistrations.getExceptionHandlerExceptionResolver() != null ? this.mvcRegistrations.getExceptionHandlerExceptionResolver() : super.createExceptionHandlerExceptionResolver();  
  287.         }  
  288.   
  289.         protected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {  
  290.             super.configureHandlerExceptionResolvers(exceptionResolvers);  
  291.             if (exceptionResolvers.isEmpty()) {  
  292.                 this.addDefaultHandlerExceptionResolvers(exceptionResolvers);  
  293.             }  
  294.   
  295.             if (this.mvcProperties.isLogResolvedException()) {  
  296.                 Iterator var2 = exceptionResolvers.iterator();  
  297.   
  298.                 while(var2.hasNext()) {  
  299.                     HandlerExceptionResolver resolver = (HandlerExceptionResolver)var2.next();  
  300.                     if (resolver instanceof AbstractHandlerExceptionResolver) {  
  301.                         ((AbstractHandlerExceptionResolver)resolver).setWarnLogCategory(resolver.getClass().getName());  
  302.                     }  
  303.                 }  
  304.             }  
  305.   
  306.         }  
  307.   
  308.         @Bean  
  309.         public ContentNegotiationManager mvcContentNegotiationManager() {  
  310.             ContentNegotiationManager manager = super.mvcContentNegotiationManager();  
  311.             List<ContentNegotiationStrategy> strategies = manager.getStrategies();  
  312.             ListIterator iterator = strategies.listIterator();  
  313.   
  314.             while(iterator.hasNext()) {  
  315.                 ContentNegotiationStrategy strategy = (ContentNegotiationStrategy)iterator.next();  
  316.                 if (strategy instanceof PathExtensionContentNegotiationStrategy) {  
  317.                     iterator.set(new WebMvcAutoConfiguration.OptionalPathExtensionContentNegotiationStrategy(strategy));  
  318.                 }  
  319.             }  
  320.   
  321.             return manager;  
  322.         }  
  323.     }  
  324.   
  325.     @Configuration  
  326.     @Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class})  
  327.     @EnableConfigurationProperties({WebMvcProperties.class, ResourceProperties.class})  
  328.     public static class WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter {  
  329.         private static final Log logger = LogFactory.getLog(WebMvcConfigurerAdapter.class);  
  330.         private final ResourceProperties resourceProperties;  
  331.         private final WebMvcProperties mvcProperties;  
  332.         private final ListableBeanFactory beanFactory;  
  333.         private final HttpMessageConverters messageConverters;  
  334.         final WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer resourceHandlerRegistrationCustomizer;  
  335.   
  336.         public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties, ListableBeanFactory beanFactory, @Lazy HttpMessageConverters messageConverters, ObjectProvider<WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider) {  
  337.             this.resourceProperties = resourceProperties;  
  338.             this.mvcProperties = mvcProperties;  
  339.             this.beanFactory = beanFactory;  
  340.             this.messageConverters = messageConverters;  
  341.             this.resourceHandlerRegistrationCustomizer = (WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer)resourceHandlerRegistrationCustomizerProvider.getIfAvailable();  
  342.         }  
  343.   
  344.         public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {  
  345.             converters.addAll(this.messageConverters.getConverters());  
  346.         }  
  347.   
  348.         public void configureAsyncSupport(AsyncSupportConfigurer configurer) {  
  349.             Long timeout = this.mvcProperties.getAsync().getRequestTimeout();  
  350.             if (timeout != null) {  
  351.                 configurer.setDefaultTimeout(timeout.longValue());  
  352.             }  
  353.   
  354.         }  
  355.   
  356.         public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {  
  357.             Map<String, MediaType> mediaTypes = this.mvcProperties.getMediaTypes();  
  358.             Iterator var3 = mediaTypes.entrySet().iterator();  
  359.   
  360.             while(var3.hasNext()) {  
  361.                 Entry<String, MediaType> mediaType = (Entry)var3.next();  
  362.                 configurer.mediaType((String)mediaType.getKey(), (MediaType)mediaType.getValue());  
  363.             }  
  364.   
  365.         }  
  366.   
  367.         @Bean  
  368.         @ConditionalOnMissingBean  
  369.         public InternalResourceViewResolver defaultViewResolver() {  
  370.             InternalResourceViewResolver resolver = new InternalResourceViewResolver();  
  371.             resolver.setPrefix(this.mvcProperties.getView().getPrefix());  
  372.             resolver.setSuffix(this.mvcProperties.getView().getSuffix());  
  373.             return resolver;  
  374.         }  
  375.   
  376.         @Bean  
  377.         @ConditionalOnBean({View.class})  
  378.         @ConditionalOnMissingBean  
  379.         public BeanNameViewResolver beanNameViewResolver() {  
  380.             BeanNameViewResolver resolver = new BeanNameViewResolver();  
  381.             resolver.setOrder(2147483637);  
  382.             return resolver;  
  383.         }  
  384.   
  385.         @Bean  
  386.         @ConditionalOnBean({ViewResolver.class})  
  387.         @ConditionalOnMissingBean(  
  388.             name = {"viewResolver"},  
  389.             value = {ContentNegotiatingViewResolver.class}  
  390.         )  
  391.         public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {  
  392.             ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();  
  393.             resolver.setContentNegotiationManager((ContentNegotiationManager)beanFactory.getBean(ContentNegotiationManager.class));  
  394.             resolver.setOrder(-2147483648);  
  395.             return resolver;  
  396.         }  
  397.   
  398.         @Bean  
  399.         @ConditionalOnMissingBean  
  400.         @ConditionalOnProperty(  
  401.             prefix = "spring.mvc",  
  402.             name = {"locale"}  
  403.         )  
  404.         public LocaleResolver localeResolver() {  
  405.             if (this.mvcProperties.getLocaleResolver() == org.springframework.boot.autoconfigure.web.WebMvcProperties.LocaleResolver.FIXED) {  
  406.                 return new FixedLocaleResolver(this.mvcProperties.getLocale());  
  407.             } else {  
  408.                 AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();  
  409.                 localeResolver.setDefaultLocale(this.mvcProperties.getLocale());  
  410.                 return localeResolver;  
  411.             }  
  412.         }  
  413.   
  414.         @Bean  
  415.         @ConditionalOnProperty(  
  416.             prefix = "spring.mvc",  
  417.             name = {"date-format"}  
  418.         )  
  419.         public Formatter<Date> dateFormatter() {  
  420.             return new DateFormatter(this.mvcProperties.getDateFormat());  
  421.         }  
  422.   
  423.         public MessageCodesResolver getMessageCodesResolver() {  
  424.             if (this.mvcProperties.getMessageCodesResolverFormat() != null) {  
  425.                 DefaultMessageCodesResolver resolver = new DefaultMessageCodesResolver();  
  426.                 resolver.setMessageCodeFormatter(this.mvcProperties.getMessageCodesResolverFormat());  
  427.                 return resolver;  
  428.             } else {  
  429.                 return null;  
  430.             }  
  431.         }  
  432.   
  433.         public void addFormatters(FormatterRegistry registry) {  
  434.             Iterator var2 = this.getBeansOfType(Converter.class).iterator();  
  435.   
  436.             while(var2.hasNext()) {  
  437.                 Converter<?, ?> converter = (Converter)var2.next();  
  438.                 registry.addConverter(converter);  
  439.             }  
  440.   
  441.             var2 = this.getBeansOfType(GenericConverter.class).iterator();  
  442.   
  443.             while(var2.hasNext()) {  
  444.                 GenericConverter converter = (GenericConverter)var2.next();  
  445.                 registry.addConverter(converter);  
  446.             }  
  447.   
  448.             var2 = this.getBeansOfType(Formatter.class).iterator();  
  449.   
  450.             while(var2.hasNext()) {  
  451.                 Formatter<?> formatter = (Formatter)var2.next();  
  452.                 registry.addFormatter(formatter);  
  453.             }  
  454.   
  455.         }  
  456.   
  457.         private <T> Collection<T> getBeansOfType(Class<T> type) {  
  458.             return this.beanFactory.getBeansOfType(type).values();  
  459.         }  
  460.   
  461.         public void addResourceHandlers(ResourceHandlerRegistry registry) {  
  462.             if (!this.resourceProperties.isAddMappings()) {  
  463.                 logger.debug("Default resource handling disabled");  
  464.             } else {  
  465.                 Integer cachePeriod = this.resourceProperties.getCachePeriod();  
  466.                 if (!registry.hasMappingForPattern("/webjars/**")) {  
  467.                     this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(cachePeriod));  
  468.                 }  
  469.   
  470.                 String staticPathPattern = this.mvcProperties.getStaticPathPattern();  
  471.                 if (!registry.hasMappingForPattern(staticPathPattern)) {  
  472.                     this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod));  
  473.                 }  
  474.   
  475.             }  
  476.         }  
  477.   
  478.         @Bean  
  479.         public WebMvcAutoConfiguration.WelcomePageHandlerMapping welcomePageHandlerMapping(ResourceProperties resourceProperties) {  
  480.             return new WebMvcAutoConfiguration.WelcomePageHandlerMapping(resourceProperties.getWelcomePage(), this.mvcProperties.getStaticPathPattern());  
  481.         }  
  482.   
  483.         private void customizeResourceHandlerRegistration(ResourceHandlerRegistration registration) {  
  484.             if (this.resourceHandlerRegistrationCustomizer != null) {  
  485.                 this.resourceHandlerRegistrationCustomizer.customize(registration);  
  486.             }  
  487.   
  488.         }  
  489.   
  490.         @Bean  
  491.         @ConditionalOnMissingBean({RequestContextListener.class, RequestContextFilter.class})  
  492.         public static RequestContextFilter requestContextFilter() {  
  493.             return new OrderedRequestContextFilter();  
  494.         }  
  495.   
  496.         @Configuration  
  497.         @ConditionalOnProperty(  
  498.             value = {"spring.mvc.favicon.enabled"},  
  499.             matchIfMissing = true  
  500.         )  
  501.         public static class FaviconConfiguration {  
  502.             private final ResourceProperties resourceProperties;  
  503.   
  504.             public FaviconConfiguration(ResourceProperties resourceProperties) {  
  505.                 this.resourceProperties = resourceProperties;  
  506.             }  
  507.   
  508.             @Bean  
  509.             public SimpleUrlHandlerMapping faviconHandlerMapping() {  
  510.                 SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();  
  511.                 mapping.setOrder(-2147483647);  
  512.                 mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));  
  513.                 return mapping;  
  514.             }  
  515.   
  516.             @Bean  
  517.             public ResourceHttpRequestHandler faviconRequestHandler() {  
  518.                 ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();  
  519.                 requestHandler.setLocations(this.resourceProperties.getFaviconLocations());  
  520.                 return requestHandler;  
  521.             }  
  522.         }  
  523.     }  
  524. }  



 

WebMvcProperties的源码如下:

 

[java]  view plain  copy
 
  1. //  
  2. // Source code recreated from a .class file by IntelliJ IDEA  
  3. // (powered by Fernflower decompiler)  
  4. //  
  5.   
  6. package org.springframework.boot.autoconfigure.web;  
  7.   
  8. import java.util.LinkedHashMap;  
  9. import java.util.Locale;  
  10. import java.util.Map;  
  11. import org.springframework.boot.context.properties.ConfigurationProperties;  
  12. import org.springframework.http.MediaType;  
  13. import org.springframework.validation.DefaultMessageCodesResolver.Format;  
  14.   
  15. @ConfigurationProperties(  
  16.     prefix = "spring.mvc"  
  17. )  
  18. public class WebMvcProperties {  
  19.     private Format messageCodesResolverFormat;  
  20.     private Locale locale;  
  21.     private WebMvcProperties.LocaleResolver localeResolver;  
  22.     private String dateFormat;  
  23.     private boolean dispatchTraceRequest;  
  24.     private boolean dispatchOptionsRequest;  
  25.     private boolean ignoreDefaultModelOnRedirect;  
  26.     private boolean throwExceptionIfNoHandlerFound;  
  27.     private boolean logResolvedException;  
  28.     private Map<String, MediaType> mediaTypes;  
  29.     private String staticPathPattern;  
  30.     private final WebMvcProperties.Async async;  
  31.     private final WebMvcProperties.Servlet servlet;  
  32.     private final WebMvcProperties.View view;  
  33.   
  34.     public WebMvcProperties() {  
  35.         this.localeResolver = WebMvcProperties.LocaleResolver.ACCEPT_HEADER;  
  36.         this.dispatchTraceRequest = false;  
  37.         this.dispatchOptionsRequest = true;  
  38.         this.ignoreDefaultModelOnRedirect = true;  
  39.         this.throwExceptionIfNoHandlerFound = false;  
  40.         this.logResolvedException = false;  
  41.         this.mediaTypes = new LinkedHashMap();  
  42.         this.staticPathPattern = "/**";  
  43.         this.async = new WebMvcProperties.Async();  
  44.         this.servlet = new WebMvcProperties.Servlet();  
  45.         this.view = new WebMvcProperties.View();  
  46.     }  
  47.   
  48.     public Format getMessageCodesResolverFormat() {  
  49.         return this.messageCodesResolverFormat;  
  50.     }  
  51.   
  52.     public void setMessageCodesResolverFormat(Format messageCodesResolverFormat) {  
  53.         this.messageCodesResolverFormat = messageCodesResolverFormat;  
  54.     }  
  55.   
  56.     public Locale getLocale() {  
  57.         return this.locale;  
  58.     }  
  59.   
  60.     public void setLocale(Locale locale) {  
  61.         this.locale = locale;  
  62.     }  
  63.   
  64.     public WebMvcProperties.LocaleResolver getLocaleResolver() {  
  65.         return this.localeResolver;  
  66.     }  
  67.   
  68.     public void setLocaleResolver(WebMvcProperties.LocaleResolver localeResolver) {  
  69.         this.localeResolver = localeResolver;  
  70.     }  
  71.   
  72.     public String getDateFormat() {  
  73.         return this.dateFormat;  
  74.     }  
  75.   
  76.     public void setDateFormat(String dateFormat) {  
  77.         this.dateFormat = dateFormat;  
  78.     }  
  79.   
  80.     public boolean isIgnoreDefaultModelOnRedirect() {  
  81.         return this.ignoreDefaultModelOnRedirect;  
  82.     }  
  83.   
  84.     public void setIgnoreDefaultModelOnRedirect(boolean ignoreDefaultModelOnRedirect) {  
  85.         this.ignoreDefaultModelOnRedirect = ignoreDefaultModelOnRedirect;  
  86.     }  
  87.   
  88.     public boolean isThrowExceptionIfNoHandlerFound() {  
  89.         return this.throwExceptionIfNoHandlerFound;  
  90.     }  
  91.   
  92.     public void setThrowExceptionIfNoHandlerFound(boolean throwExceptionIfNoHandlerFound) {  
  93.         this.throwExceptionIfNoHandlerFound = throwExceptionIfNoHandlerFound;  
  94.     }  
  95.   
  96.     public boolean isLogResolvedException() {  
  97.         return this.logResolvedException;  
  98.     }  
  99.   
  100.     public void setLogResolvedException(boolean logResolvedException) {  
  101.         this.logResolvedException = logResolvedException;  
  102.     }  
  103.   
  104.     public Map<String, MediaType> getMediaTypes() {  
  105.         return this.mediaTypes;  
  106.     }  
  107.   
  108.     public void setMediaTypes(Map<String, MediaType> mediaTypes) {  
  109.         this.mediaTypes = mediaTypes;  
  110.     }  
  111.   
  112.     public boolean isDispatchOptionsRequest() {  
  113.         return this.dispatchOptionsRequest;  
  114.     }  
  115.   
  116.     public void setDispatchOptionsRequest(boolean dispatchOptionsRequest) {  
  117.         this.dispatchOptionsRequest = dispatchOptionsRequest;  
  118.     }  
  119.   
  120.     public boolean isDispatchTraceRequest() {  
  121.         return this.dispatchTraceRequest;  
  122.     }  
  123.   
  124.     public void setDispatchTraceRequest(boolean dispatchTraceRequest) {  
  125.         this.dispatchTraceRequest = dispatchTraceRequest;  
  126.     }  
  127.   
  128.     public String getStaticPathPattern() {  
  129.         return this.staticPathPattern;  
  130.     }  
  131.   
  132.     public void setStaticPathPattern(String staticPathPattern) {  
  133.         this.staticPathPattern = staticPathPattern;  
  134.     }  
  135.   
  136.     public WebMvcProperties.Async getAsync() {  
  137.         return this.async;  
  138.     }  
  139.   
  140.     public WebMvcProperties.Servlet getServlet() {  
  141.         return this.servlet;  
  142.     }  
  143.   
  144.     public WebMvcProperties.View getView() {  
  145.         return this.view;  
  146.     }  
  147.   
  148.     public static enum LocaleResolver {  
  149.         FIXED,  
  150.         ACCEPT_HEADER;  
  151.   
  152.         private LocaleResolver() {  
  153.         }  
  154.     }  
  155.   
  156.     public static class View {  
  157.         private String prefix;  
  158.         private String suffix;  
  159.   
  160.         public View() {  
  161.         }  
  162.   
  163.         public String getPrefix() {  
  164.             return this.prefix;  
  165.         }  
  166.   
  167.         public void setPrefix(String prefix) {  
  168.             this.prefix = prefix;  
  169.         }  
  170.   
  171.         public String getSuffix() {  
  172.             return this.suffix;  
  173.         }  
  174.   
  175.         public void setSuffix(String suffix) {  
  176.             this.suffix = suffix;  
  177.         }  
  178.     }  
  179.   
  180.     public static class Servlet {  
  181.         private int loadOnStartup = -1;  
  182.   
  183.         public Servlet() {  
  184.         }  
  185.   
  186.         public int getLoadOnStartup() {  
  187.             return this.loadOnStartup;  
  188.         }  
  189.   
  190.         public void setLoadOnStartup(int loadOnStartup) {  
  191.             this.loadOnStartup = loadOnStartup;  
  192.         }  
  193.     }  
  194.   
  195.     public static class Async {  
  196.         private Long requestTimeout;  
  197.   
  198.         public Async() {  
  199.         }  
  200.   
  201.         public Long getRequestTimeout() {  
  202.             return this.requestTimeout;  
  203.         }  
  204.   
  205.         public void setRequestTimeout(Long requestTimeout) {  
  206.             this.requestTimeout = requestTimeout;  
  207.         }  
  208.     }  
  209. }  



 

2,自动配置的静态资源

    在自动配置类的addResourceHandlers方法中定义了以下静态资源的自动配置。

1)类路径文件

    把类路径下的/static,/public,/resources和/META-INF/resources文件夹下的静态文件直接映射为/**,可以通过http://localhost:8080/**来访问。

 

2)webjar

        何谓webjar,webjar就是将是我们常用的脚本框架封装在jar包中的jar包,更多关于webjar的内容请访问http://www.webjars.org网站

    把webjar的/META-INF/resources/webjars/下的静态文件映射为/webjar/**,可以通过http://localhost:8080/webjar/**来访问

     

3,自动配置的Formatter和Converter

     关于自动配置的Formatter和Converter,我们可以看一下WebMvcAutoConfiguration类中的定义:

 

[java]  view plain  copy
 
  1. public void addFormatters(FormatterRegistry registry) {  
  2.             Iterator var2 = this.getBeansOfType(Converter.class).iterator();  
  3.   
  4.             while(var2.hasNext()) {  
  5.                 Converter<?, ?> converter = (Converter)var2.next();  
  6.                 registry.addConverter(converter);  
  7.             }  
  8.   
  9.             var2 = this.getBeansOfType(GenericConverter.class).iterator();  
  10.   
  11.             while(var2.hasNext()) {  
  12.                 GenericConverter converter = (GenericConverter)var2.next();  
  13.                 registry.addConverter(converter);  
  14.             }  
  15.   
  16.             var2 = this.getBeansOfType(Formatter.class).iterator();  
  17.   
  18.             while(var2.hasNext()) {  
  19.                 Formatter<?> formatter = (Formatter)var2.next();  
  20.                 registry.addFormatter(formatter);  
  21.             }  
  22.   
  23.         }  


      从代码中可以看出,只要我们定义了Converter,GenericConverter和Formatter接口的事项类的Bean,这些Bean就会自动注册到Spring MVC中。

 

4,自动配置的HttpMessageConverters

    在WebMvcAutoConfiguration中,我们注册了messageConverters,代码如下:

 

[java]  view plain  copy
 
  1. @Configuration  
  2.     @Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class})  
  3.     @EnableConfigurationProperties({WebMvcProperties.class, ResourceProperties.class})  
  4.     public static class WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter {  
  5.         private static final Log logger = LogFactory.getLog(WebMvcConfigurerAdapter.class);  
  6.         private final ResourceProperties resourceProperties;  
  7.         private final WebMvcProperties mvcProperties;  
  8.         private final ListableBeanFactory beanFactory;  
  9.         private final HttpMessageConverters messageConverters;  
  10.         final WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer resourceHandlerRegistrationCustomizer;  
  11.   
  12.         public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties, ListableBeanFactory beanFactory, @Lazy HttpMessageConverters messageConverters, ObjectProvider<WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider) {  
  13.             this.resourceProperties = resourceProperties;  
  14.             this.mvcProperties = mvcProperties;  
  15.             this.beanFactory = beanFactory;  
  16.             this.messageConverters = messageConverters;  
  17.             this.resourceHandlerRegistrationCustomizer = (WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer)resourceHandlerRegistrationCustomizerProvider.getIfAvailable();  
  18.         }  
  19.   
  20.         public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {  
  21.             converters.addAll(this.messageConverters.getConverters());  
  22.         }  
  23.   
  24.         public void configureAsyncSupport(AsyncSupportConfigurer configurer) {  
  25.             Long timeout = this.mvcProperties.getAsync().getRequestTimeout();  
  26.             if (timeout != null) {  
  27.                 configurer.setDefaultTimeout(timeout.longValue());  
  28.             }  
  29.   
  30.         }  



 

 

       在这里直接注入了HttpMessageConverters的Bean,而这个Bean是在HttpMessageConvertersAutoConfiguration类中定义的,我们自动扫描注册的HttpMessage Converter除了Spring MVC默认的ByteArrayHttpMessageConverter,StringHttpMessage Converter,Resource HttpMessageConverter等外,还自动配置文件里引入了JacksonHttpMessageConverters Configuration和GsonHttpMessage ConverterConfiguration,使我们获得了额外的HttpMessageConverter:

      若jackson的jar包在路径上,则Spring Boot通过JacksonHttpMessage Converters Configuration增加了MappingJackson2HttpMessage Converter和Mapping Jackson2XmlHttpMessageConverter

     若gson的jar包在路径上,则Spring Boot通过GsonHttpMessageConverterConfiguration增加GsonHttpMessageConverter

      在Spring Boot中如果要新增自定义的HttpMessageConverter,则只需定义一个你自己的HttpMessageConverters的Bean,然后在此Bean中注册自定义的HttpMessageConverter即可,如下:

 

[java]  view plain  copy
 
  1. @Bean  
  2.     public HttpMessageConverters customConverters(){  
  3.         HttpMessageConverter<?> customConverter1 = new CustomConverter1();  
  4.         HttpMessageConverter<?> customConverter2 = new CustomConverter2();  
  5.         return new HttpMessageConverters(customConverter1,customConverter2)  
  6.     }  



 

5,静态首页的支持

把静态index.html文件放置在如下目录

classpath:/META-INF/resources/index.html

 

classpath:/resources/index.html

classpath:/static/index.html

classpath:/public/index.html

当我们访问应用根目录http://localhost:8080/时,会直接映射

 

二:接管Spring Boot的Web配置

        如果Spring Boot提供的Spring MVC默认配置不符合需求,则可以通过一个配置类(注解有@Configuration的类)加上@EnableWebMvc注解来实现完全自己控制的MVC配置。

       通常情况下,Spring Boot的自动配置是符合我们大多数需求的。在你既需要保留Spring Boot提供的便利,又需要增加自己额外的配置的时候,可以定义一个配置类并继承WebMvcConfigurerAdapter,无须使用@EnableWebMvc,例如:

 

[java]  view plain  copy
 
  1. package jack.springmvc.config;  
  2.   
  3. import jack.springmvc.interceptor.DemoInterceptor;  
  4. import jack.springmvc.messageconverter.MyMessageConverter;  
  5. import org.springframework.context.annotation.Bean;  
  6. import org.springframework.context.annotation.ComponentScan;  
  7. import org.springframework.context.annotation.Configuration;  
  8. import org.springframework.http.converter.HttpMessageConverter;  
  9. import org.springframework.scheduling.annotation.EnableScheduling;  
  10. import org.springframework.web.multipart.MultipartResolver;  
  11. import org.springframework.web.multipart.commons.CommonsMultipartResolver;  
  12. import org.springframework.web.servlet.config.annotation.*;  
  13. import org.springframework.web.servlet.view.InternalResourceViewResolver;  
  14. import org.springframework.web.servlet.view.JstlView;  
  15.   
  16. import java.util.List;  
  17.   
  18. /** 
  19.  * Created by jack on 2017/7/16. 
  20.  */  
  21. @Configuration  
  22. @EnableWebMvc   //开启Spring MVC支持,若无此句,重写WebMvcConfigurerAdapter方法无效  
  23. @ComponentScan("jack.springmvc")  
  24. @EnableScheduling   //开启计划任务的支持  
  25. //继承WebMvcConfigurerAdapter类,重写其方法可对Spring MVC进行配置  
  26. public class MyMvcConfig extends WebMvcConfigurerAdapter{  
  27.   
  28.     /** 
  29.      * 配置拦截器的Bean 
  30.      * @return 
  31.      */  
  32.     @Bean  
  33.     public DemoInterceptor demoInterceptor(){  
  34.         return new DemoInterceptor();  
  35.     }  
  36.   
  37.     /** 
  38.      * 配置文件上传Bean 
  39.      * @return 
  40.      */  
  41.     @Bean  
  42.     public MultipartResolver multipartResolver(){  
  43.         CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();  
  44.         multipartResolver.setMaxUploadSize(1000000);  
  45.         return multipartResolver;  
  46.     }  
  47.   
  48.     /** 
  49.      * c重写addInterceptors方法,注册拦截器 
  50.      * @param registry 
  51.      */  
  52.     @Override  
  53.     public void addInterceptors(InterceptorRegistry registry) {  
  54.         //super.addInterceptors(registry);  
  55.         registry.addInterceptor(demoInterceptor());  
  56.     }  
  57.   
  58.     @Bean  
  59.     public InternalResourceViewResolver viewResolver(){  
  60.         InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();  
  61.         //viewResolver.setPrefix("/WEB-INF/classes/views/");  
  62.         viewResolver.setPrefix("/WEB-INF/classes/views/");  
  63.         viewResolver.setSuffix(".jsp");  
  64.         viewResolver.setViewClass(JstlView.class);  
  65.         return  viewResolver;  
  66.     }  
  67.   
  68.     @Override  
  69.     public void addResourceHandlers(ResourceHandlerRegistry registry) {  
  70.         //super.addResourceHandlers(registry);  
  71.         //addResourceLocations指的是文件放置的目录,addResourceHandler指的是对外暴露的访问路径  
  72.         registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");  
  73.     }  
  74.   
  75.     /**  
  76.      * 统一处理没啥业务逻辑处理的controller请求,实现代码的简洁  
  77.      * @param registry  
  78.      */  
  79.     @Override  
  80.     public void addViewControllers(ViewControllerRegistry registry) {  
  81.         //super.addViewControllers(registry);  
  82.         registry.addViewController("/index").setViewName("/index");  
  83.         registry.addViewController("/toUpload").setViewName("upload");  
  84.         registry.addViewController("/converter").setViewName("/converter");  
  85.         registry.addViewController("/sse").setViewName("/sse");  
  86.         registry.addViewController("/async").setViewName("/async");  
  87.     }  
  88.   
  89.     @Override  
  90.     public void configurePathMatch(PathMatchConfigurer configurer) {  
  91.         //super.configurePathMatch(configurer);  
  92.         configurer.setUseSuffixPatternMatch(false);  
  93.     }  
  94.   
  95.     /** 
  96.      * 配置自定义的HttpMessageConverter的bean,在spring mvc里注册HttpMessageConverter有两个方法: 
  97.      * configureMessageConverters:重载会覆盖掉Spring MVC默认注册的多个HttpMessageConverter 
  98.      * extendMessageConverters:仅添加一个自定义的HttpMessageConverter,不覆盖默认注册的HttpMessageConverter 
  99.      * @param converters 
  100.      */  
  101.     @Override  
  102.     public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {  
  103.         //super.extendMessageConverters(converters);  
  104.         converters.add(converter());  
  105.     }  
  106.   
  107.     @Bean  
  108.     public MyMessageConverter converter(){  
  109.         return new MyMessageConverter();  
  110.     }  
  111.   
  112. }  


     上注意,上面重写了了addViewController方法,并不会覆盖WebMvcAutoConfiguration中的addViewController(在此方法中Spring Boot将“/”映射至index.html),这也就意味着我们自己的配置和Spring Boot的自动配置同时有效,这也是推荐添加自己的MVC配置的方式。

 

 

三:接注册Servlet,Filter,Listener

      当使用嵌入式的Servlet容器时,我们通过将Servlet,Filter和Listener声明为Spring Bean而达到注册的效果;或者注册ServletRegistrationBean,FilterRegistrationBean和ServletListenerRegistrationBean的Bean。

1)直接注册Bean示例,代码如下:

 

[java]  view plain  copy
 
  1. @Bean  
  2.     public XxServlet xxServlet(){  
  3.         return new XxServlet();  
  4.     }  
  5.       
  6.     @Bean  
  7.     public YyFilter yyFilter(){  
  8.         return new YyFilter();  
  9.     }  
  10.       
  11.     @Bean  
  12.     public ZzListener zzListener(){  
  13.         return new ZzListener()  
  14.     }  



 

2)通过RegistrationBean

 

[java]  view plain  copy
 
    1. @Bean  
    2.    public ServeletRegistrationBean serveletRegistrationBean(){  
    3.        return new ServeletRegistrationBean(new Xxservlet(),"/xx/*");  
    4.    }  
    5.      
    6.    @Bean  
    7.    public FilterRegistrationBean filterRegistrationBean(){  
    8.        FilterRegistrationBean registrationBean = new FilterRegistrationBean();  
    9.        registrationBean.setFilter(new YyFilter());  
    10.        registrationBean.setOrder(2);  
    11.        return registrationBean;  
    12.    }  
    13.    @Bean  
    14.    public ServletListenerRegistrationBean<ZzListener> zzListenerServletListenerRegistrationBean(){  
    15.        return new ServletListenerRegistrationBean<ZzListener>(new ZzListener())  

转载于:https://www.cnblogs.com/pangguoming/p/8144498.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值