springboot使用WebMvcConfigurerAdapter添加javabean配置(Interceptor/messageConvert等)
程序员文章站
2022-04-19 21:27:05
...
WebMvcConfigurerAdapter
配置类其实是Spring
内部的一种配置方式,我们可以在里面声明一些javabean来进行个性化的定制
继承WebMvcConfigurerAdapter类,并加上@Configuration注解
1、拦截器 ,只要重写 addInterceptors方法就可以添加拦截器
@Configuration
public class LocaleConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
registry.addInterceptor(localeChangeInterceptor);
}
}
2.添加自定义的消息转换器
@Configuration
public class FastJsonConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//父类方法,
super.configureMessageConverters(converters);
//新建一个消息转换器
FastJsonHttpMessageConverter messageConverter=new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig=new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue
);
messageConverter.setFastJsonConfig(fastJsonConfig);
//添加消息转换器
converters.add(messageConverter);
}
}
参考:https://blog.csdn.net/u012129558/article/details/79006253