【SpringBoot重写配置的方法】

【SpringBoot重写配置的方法】,第1张

文章目录
  • 不用@EnableWebMvc注解,使用 @Configuration + WebMvcConfigurer 自定义规则
    • 方法一:实现WebMvcConfigurer接口
    • 方法二:容器中放一个WebMvcConfigurer
  • 重写addFormatters配置函数

新版默认为false

不用@EnableWebMvc注解,使用 @Configuration + WebMvcConfigurer 自定义规则

自定义一个配置类实现接口WebMvcConfigurer
jdk8有接口的默认实现,我们只需要重写我们想重写的方法即可。

方法一:实现WebMvcConfigurer接口
@Configuration(proxyBeanMethods = false)
public class MyConfig implements WebMvcConfigurer{
    //@Bean
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        //UrlPathHelper
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        //不移除分号后面的内容,矩阵变量功能才能生效
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}
方法二:容器中放一个WebMvcConfigurer

@Configuration(proxyBeanMethods = false)
public class MyConfig{
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            @Override
            public void configurePathMatch(PathMatchConfigurer configurer) {
                UrlPathHelper urlPathHelper = new UrlPathHelper();
                urlPathHelper.setRemoveSemicolonContent(false);
                configurer.setUrlPathHelper(urlPathHelper);
            }
        };
    }
}

重写addFormatters配置函数
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new Converter<String, Pet>() {
            @Override
            public Pet convert(String source) {
                if(StringUtils.hasText(source)){
                    Pet pet = new Pet();
                    String[] split = source.split(",");
                    pet.setName(split[0]);
                    pet.setAge(split[1]);
                    return pet;
                }
                return null;
            }
        });
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/874894.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存