在SpringBoot中我们有时会要自己来写一些配置类,只要我们把写好的配置类放在Configuration容器中再运行程序就可以使用了,那其中的原理到底是怎么样的呢?
//我们自己写的配置类
@Configuration
public class MyAppConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送/ok请求来到静态资源文件夹中的hello.html
registry.addViewController("/ok").setViewName("hello");
}
}
保留了所有的自动配置,也能用我们扩展的配置
原理:
1.WebMvcAutoConfiguration是SpringMVC的自动配置类
2.WebMvcAutoConfiguration类在做其他自动配置时会导入:@Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class})
@Configuration
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {
//在上面类继承的父类DelegatingWebMvcConfiguration中有如下代码
//从容器中获取所有的WebMvcConfiguration
//自己写的配置类也放在了容器中所以可以被调用
@Autowired(
required = false
)
public void setConfigurers(List<WebMvcConfigurer> configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
}
}
//通过遍历来找到所有的WebMvcConfigurer
public void addViewControllers(ViewControllerRegistry registry) {
Iterator var2 = this.delegates.iterator();
while(var2.hasNext()) {
WebMvcConfigurer delegate = (WebMvcConfigurer)var2.next();
delegate.addViewControllers(registry);
}
}
3.容器中所有的WebMvcConfigurer都会一起起作用
4.我们自己写的配置类也会被调用
当前还在学习中,有错误还请大家多多指正哦