SpringBoot-MVC配置

springboot自动配置原理

@EnableAutoConfiguration

  1. SpringBoot启动会加载大量的自动配置类。xxxxAutoConfigurartion:每一个这样的 xxxAutoConfiguration类都是容器中的一个组件,都加入到容器中;
  2. 每一个自动配置类进行自动配置功能;(类中通过@bean注册组件)
  3. 在全局配置文件中的配置通过@ConfigurationProperties绑定到相对应的Properties结尾的配置类。xxxxProperties:封装配置文件中相关属性(我们就可以在配置文件中指定这些属性的值)
  4. 通过@EnableConfigurationProperties注解将properties结尾的配置类注入到spring容器中
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(HttpProperties.class)
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)

------------------------------------------

@Bean //给容器中添加一个组件,这个组件的某些值需要从properties中获取
@ConditionalOnMissingBean(CharacterEncodingFilter.class) //判断容器没有这个组件?
public CharacterEncodingFilter characterEncodingFilter() {
	CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
	filter.setEncoding(this.properties.getCharset().name());
	filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
	filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));
	return filter;

回顾springmvc的组件

详见此博客
1. 前端控制器组件(DispatcherServlet)
2. 处理器组件(Controller)
3. 处理器映射器组件(HandlerMapping)
4. 处理器适配器组件(HandlerAdapter)
5. 拦截器组件(HandlerInterceptor)
6. 视图解析器组件(ViewResolver)
7. 视图组件(View)
8. 数据转换组件(DataBinder)
9. 消息转换器组件(HttpMessageConverter)

springmvc自动配置

  • 引入ContentNegotiatingViewResolver和BeanNameViewResolver beans。
  • 对静态资源的支持,包括对WebJars的支持。 自动注册Converter,GenericConverter,Formatter beans。
  • 对HttpMessageConverters的支持。
  • 自动注册MessageCodeResolver。
  • 对静态index.html的支持。
  • 对自定义Favicon的支持。
  • 自动使用ConfigurableWebBindingInitializer bean。

ContentNegotiatingViewResolver,Converter,Formatter(HttpMessageConverters)
1)、SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默
认的组合起来;
例子:国际化的点击实现,需要自己修改LocaleResolver.

  1. public class MyLocaleResolver implements LocaleResolver{ … }
  2. 在配置类中注册该组件

2)、在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置
3)、在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置

扩展MVC

如果我们想要add additional MVC configuration (interceptors 拦截器, formatters 格式转换器, view controllers 视图处理器, and other features)
比如之前采用的xml配置方式:
在这里插入图片描述

  • 方法:
  1. 编写一个@Configuration注解类,并且实现WebMvcConfigurer接口,还不能标注@EnableWebMvc注解
  2. 要什么功能就重写什么方法
//应为类型要求为WebMvcConfigurer,所以我们实现其接口
//可以使用自定义类扩展MVC的功能
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

	//添加视图映射规则
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 浏览器发送/test , 就会跳转到test页面;
        registry.addViewController("/test").setViewName("test");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值