扩展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,在实际开发中,不建议这样做!

posted @   学海无涯#  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示