扩展SpringMVC配置
前言
学习Spring Boot一定要多看源码,多看官方文档!
静态资源(html/css/js)可以存放的位置
看源码,一步一步去找官方的设置!
WebMvcAutoConfiguration是web环境的自动配置类,在这个类里面有一个静态内部类WebMvcAutoConfigurationAdapter,类WebMvcAutoConfigurationAdapter里面有一个处理资源的方法addResourceHandlers():
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (this.servletContext != null) {
ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
registration.addResourceLocations(resource);
}
});
}
可以看到它是通过addResourceLocations(this.resourceProperties.getStaticLocations())去寻找资源路径的,而在构造器里可以找到this.resourceProperties = webProperties.getResources();
webProperties类:
public class WebProperties {
...
private final Resources resources = new Resources();
...
public Resources getResources() {
return this.resources;
}
public static class Resources {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
/**
* Locations of static resources. Defaults to classpath:[/META-INF/resources/,
* /resources/, /static/, /public/].
*/
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
...
public String[] getStaticLocations() {
return this.staticLocations;
}
...
}
所以this.resourceProperties.getStaticLocations()得到的就是{ "classpath:/META-INF/resources/","classpath:/resources/", "classpath:/static/", "classpath:/public/" }这四个路径。终上,得出我们能够存放静态资源的位置。
扩展Spring MVC的配置
除了Spring Boot默认帮我们配置的组件,我们还可以自定义组件让Spring Boot在启动时帮我们装配!官方文档相关的说明:
If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.
所以我们要做的就是编写一个@Configuration注解类,并且实现接口WebMvcConfigurer,注意不能标注@EnableWebMvc注解;不能标注@EnableWebMvc注解的原因是:WebMvcAutoConfiguration配置类上有一个条件注解@ConditionalOnMissingBean(WebMvcConfigurationSupport.class),也就是说WebMvcAutoConfiguration配置类生效的条件之一是Spring容器里面没有注册WebMvcConfigurationSupport这个类,而@EnableWebMvc会向容器中注入类DelegatingWebMvcConfiguration,这个类继承了WebMvcConfigurationSupport(它只是SpringMVC最基本的功能)。所以加了@EnableWebMvc会导致web的自动配置类失效,这就意味着我们要全面接管SpringMVC,在实际开发中,不建议这样做!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?