zoukankan      html  css  js  c++  java
  • SpringBoot 2.0 编程方式配置,不使用默认配置方式

    SpringBoot的一般配置是直接使用application.properties或者application.yml,因为SpringBoot会读取.perperties和yml文件来覆盖默认配置;

    从源码分析SpringBoot默认配置是怎样的

    ResourceProperties 这个class说明了springboot默认读取的properties

        private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
        			"classpath:/META-INF/resources/", "classpath:/resources/",
        			"classpath:/static/", "classpath:/public/" };
    

    WebMvcAutoConfiguration 这个class就是springboot默认的mvc配置类,里面有一个static class实现了WebMvcConfigurer接口,;具体这个接口有什么用,具体可以看spring官网[springMVC配置][1]

        @Configuration
    	@Import(EnableWebMvcConfiguration.class)
    	@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
    	@Order(0)
        public static class WebMvcAutoConfigurationAdapter
        			implements WebMvcConfigurer, ResourceLoaderAware 
    

    可以看到里面的默认viewResolver配置,只要我们复写了ViewResolver这个bean,就相当于不适用SpringBoot的默认配置;

    		@Bean
    		@ConditionalOnMissingBean
    		public InternalResourceViewResolver defaultViewResolver() {
    			InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    			resolver.setPrefix(this.mvcProperties.getView().getPrefix());
    			resolver.setSuffix(this.mvcProperties.getView().getSuffix());
    			return resolver;
    		}
    

    这里里面有一个很常见的mapping,在springboot启动日志中就可以看到。

    			@Bean
    			public SimpleUrlHandlerMapping faviconHandlerMapping() {
    				SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
    				mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
    				mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
    						faviconRequestHandler()));
    				return mapping;
    			}
    ```
    
    实验证明,通过实现了`WebMvcConfigurer`接口的bean具有优先级 (或者继承`WebMvcConfigurationSupport`),会覆盖在.properties中的配置。比如`ViewResolver`
    
    ### 编程方式配置SpringBoot例子
    
    2种方式,1是实现`WebMvcConfigurer `接口,2是继承`WebMvcConfigurationSupport`;(其实还有第三种,就是继承`WebMvcConfigurerAdapter`,但是这种方式在Spring 5中被舍弃)
    
    
    
      [1]: https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html
  • 相关阅读:
    PAT1137
    Ubuntu小工具
    C文件的格式化工具(astyle)
    linux批量替换文本字符串
    scp & cat远程文件操作
    上传附件中英文混合的文件名上传
    membership DB生成 & dll 强命名 & 证书生成
    机器Coding For WinForm
    机器Coding For WPF
    C# cmd bcp 导出数据
  • 原文地址:https://www.cnblogs.com/chenjingquan/p/9194545.html
Copyright © 2011-2022 走看看