美文网首页
Springboot MVC模块

Springboot MVC模块

作者: hcq0514 | 来源:发表于2019-06-26 17:56 被阅读0次

MVC官方文档地址

Spring MVC Auto-configuration

Spring Boot provides auto-configuration for Spring MVC that works well with most applications.

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

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
  • Support for serving static resources, including support for WebJars
  • Automatic registration of Converter, GenericConverter, and Formatter beans.
  • Support for HttpMessageConverters (covered later in this document).
  • Automatic registration of MessageCodesResolver (covered later in this document).
  • Static index.html support.
  • Custom Favicon support (covered later in this document).
  • Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).

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

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

// 如果需要拓展mvc的功能的话,可以继承WebMvcRegistrationsAdapter类,如果想完全控制mvc的话,可以加@EnableWebMvc

WebMvcProperties 配置文件

@ConfigurationProperties(prefix = "spring.mvc")
public class WebMvcProperties {
    private DefaultMessageCodesResolver.Format messageCodesResolverFormat; //自定义错误编码
    private Locale locale; //用于国际化
    private LocaleResolver localeResolver = LocaleResolver.ACCEPT_HEADER;
    private String dateFormat; //日期格式化
    private boolean dispatchTraceRequest = false;
    private boolean dispatchOptionsRequest = true;
    private boolean ignoreDefaultModelOnRedirect = true;
    private boolean throwExceptionIfNoHandlerFound = false;
    private boolean logResolvedException = false;
    private String staticPathPattern = "/**"; // 静态文件默认路径

对上面自动配置进行具体解释

1. 注入ContentNegotiatingViewResolver and BeanNameViewResolver beans.

        @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;
        }

    @Bean
        @ConditionalOnBean(View.class)
        @ConditionalOnMissingBean
        public BeanNameViewResolver beanNameViewResolver() {
            BeanNameViewResolver resolver = new BeanNameViewResolver();
            resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
            return resolver;
        }

2. Static Content (静态内容默认配置地址)
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/**
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/" };

    /**
     * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
     * /resources/, /static/, /public/].
     */
    private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

3. 自动注入Converter, GenericConverter, and Formatter beans.

  • Converter 转换器; public String hello(User user):类型转换使用Converter
  • Formatter 格式化器; 2017.12.17===Date;

4. 获取HttpMessageConverters

  • HttpMessageConverter:是SpringMVC用来转换Http请求和响应的;User---Json
  • 获取所有的HttpMessageConverter

5. 注入MessageCodesResolver 用于定义错误代码生成规则

        @Override
        public MessageCodesResolver getMessageCodesResolver() {
// 从mvcProperties取是否有配置这个东西,如果有的话就注入
            if (this.mvcProperties.getMessageCodesResolverFormat() != null) {
                DefaultMessageCodesResolver resolver = new DefaultMessageCodesResolver();
                resolver.setMessageCodeFormatter(
                        this.mvcProperties.getMessageCodesResolverFormat());
                return resolver;
            }
            return null;
        }

6. Static index.html support. 静态主页支持

@Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(
                ApplicationContext applicationContext) {
            return new WelcomePageHandlerMapping(
                    new TemplateAvailabilityProviders(applicationContext),
                    applicationContext, getWelcomePage(),
                    this.mvcProperties.getStaticPathPattern());
        }
//接上面方法
    WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
            ApplicationContext applicationContext, Optional<Resource> welcomePage,
            String staticPathPattern) {
        if (welcomePage.isPresent() && "/**".equals(staticPathPattern)) {
            logger.info("Adding welcome page: " + welcomePage.get());
            setRootViewName("forward:index.html"); //去根目录下找index.html页面
        }
        else if (welcomeTemplateExists(templateAvailabilityProviders,
                applicationContext)) {
            logger.info("Adding welcome page template: index");
            setRootViewName("index");
        }
    }

7. Custom Favicon support 用户自定义网站图标支持

        @Configuration
        @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
        public static class FaviconConfiguration implements ResourceLoaderAware {

            private final ResourceProperties resourceProperties;

            private ResourceLoader resourceLoader;

            public FaviconConfiguration(ResourceProperties resourceProperties) {
                this.resourceProperties = resourceProperties;
            }

            @Override
            public void setResourceLoader(ResourceLoader resourceLoader) {
                this.resourceLoader = resourceLoader;
            }

            @Bean
            public SimpleUrlHandlerMapping faviconHandlerMapping() {
                SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
                mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
// 找到所有 **/favicon.ico
                mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
                        faviconRequestHandler()));
                return mapping;
            }

            @Bean
            public ResourceHttpRequestHandler faviconRequestHandler() {
                ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
                requestHandler.setLocations(resolveFaviconLocations());
                return requestHandler;
            }

// 设置默认位置为/
            private List<Resource> resolveFaviconLocations() {
                String[] staticLocations = getResourceLocations(
                        this.resourceProperties.getStaticLocations());
                List<Resource> locations = new ArrayList<>(staticLocations.length + 1);
                Arrays.stream(staticLocations).map(this.resourceLoader::getResource)
                        .forEach(locations::add);
                locations.add(new ClassPathResource("/"));
                return Collections.unmodifiableList(locations);
            }

        }

8. Automatic use of a ConfigurableWebBindingInitializer bean .

相关文章

  • Springboot MVC模块

    MVC官方文档地址 Spring MVC Auto-configuration Spring Boot provi...

  • Spring Boot配置

    SpringBoot配置属性之MVC SpringBoot配置属性之Server SpringBoot配置属性之D...

  • Spring Boot

    SpringBoot模块分类: spring-boot模块 该模块提供了一些特性用来支持springboot中其他...

  • 前端 MVC、MVVM 与面向对象

    按照《前端MVC与模块化》中的方法把各模块代码分成MVC三层,仍然存在一些问题,如公共方法无法复用、每个模块MVC...

  • springboot简单整合dubbo的小demo(基于yml配

    顺便学习一下springboot如何搭建分模块项目 创建分模块springboot 先创建一个springboot...

  • 虚拟环境

    软件框架:由其中的各个模块组成的,每个模块负责特定的功能,模块与模块之间相互协作来完成软件开发。 MVC:MVC框...

  • DAY07-Sping04

    一、Spring Web框架 MVC思想 Spring MVC Servlet:Web 服务的模块,包含对 MVC...

  • 2019-07-02SpringBoot之Web开发

    使用SpringBoot; 1)、创建SpringBoot应用,选中我们需要的模块;2)、SpringBoot已经...

  • SpringBoot的web开发

    使用SpringBoot; 1)、创建SpringBoot应用,选中我们需要的模块; 2)、SpringBoot已...

  • 一、Spring MVC 基础知识

    Spring MVC 基础知识 简介 Spring MVC是 Spring 框架的一个模块,Spring MVC ...

网友评论

      本文标题:Springboot MVC模块

      本文链接:https://www.haomeiwen.com/subject/zwsccctx.html