SpringBoot之SpringMVC自动配置
- 更多分享:www.catbro.cn
一、前言:
- 对于一般应用而言,spring boot对Spring mvc的自动化配置能很好的满足需求了。
二、自动化配置所带来的新特新。
- ContentNegotiatingViewResolver
- BeanNameViewResolver
- 支持多种静态资源
- 支持 HttpMessageConverters(自动注册):负责处理http请求和响应、解析json或者xml,默认编码UTF-8
- 静态 index.html 支持
- 自定义 Favicon
- 自动使用 ConfigurableWebBindingInitializer
三、增加特性
-
If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type WebMvcConfigurerAdapter, but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver you can declare a WebMvcRegistrationsAdapter instance providing such components.
-
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.
增加自定义转换器
-
代码如下
import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.context.annotation.*; import org.springframework.http.converter.*; @Configuration public class MyConfiguration { @Bean public HttpMessageConverters customConverters() { HttpMessageConverter<?> additional = ... HttpMessageConverter<?> another = ... return new HttpMessageConverters(additional, another); } }
自定义json 序列化和反序列化
-
一般不需要自定义
-
@JsonComponent标记的类将会被Spring 自动加载,在进行json的操作时将通过JsonSerializer和JsonDeserializerz 这两个类来实现
-
Spring Boot也提供来JsonObjectSerializer and JsonObjectDeserializer b两个操作json的基类便于用户扩展。
import java.io.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import org.springframework.boot.jackson.*; @JsonComponent public class Example { public static class Serializer extends JsonSerializer<SomeObject> { // ... } public static class Deserializer extends JsonDeserializer<SomeObject> { // ... } }