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配置

    @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中被舍弃)

一个整合了mybatis,jsp的SpringBoot编程方式配置在我的GitHub中给出,欢迎大家star;
springboot-config-programmatically

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值