官网给出 :大多场景我们都无需自定义配置
给出了很多的默认的Spring资源 : Beans 、 静态资源 、 自动注册等等
如果我们想要自己配置来添加更多的:
不用@EnableWebMvc注解。使用 @Configuration
+ WebMvcConfigurer
自定义规则
/static
(or /public
or /resources
or /META-INF/resources
访问 : 当前项目根路径/ + 静态资源名
请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面
在配置文件application.yaml添加前缀
spring:
mvc:
static-path-pattern: /res/**
# 上面的作用就是 res下面的所有请求都是静态请求
# 然后,我们当前项目访问静态资源就是 : 当前项目名 + 静态项目前缀 + 静态资源名
resources:
static-location: [classpath:/XXX/]
# 将所有的静态资源都放在resources下的XXX文件夹下
也就是默认根路径
因为底层这个是被写死的,没办法修改
类似这样:
名字为: favicon.ico 的 放在静态资源目录下即可。
自动配置生效
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
//如果实现了定制化的配置, 那么这个配置类中的所有方法都不会生效
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
}
它给容器中配置了什么
3. 在WebMvcAutoConfiguration中有一个静态内部类 就是下面的这个
@Configuration(proxyBeanMethods = false)
@Import(EnableWebMvcConfiguration.class)
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {
}
从@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
这个注解 ,我们可以知道 ,其中的相关属性就会和 XXX (配置文件) 进行绑定
WebMvcProperties 和前缀为spring.mvc相关的进行绑定
ResourceProperties 和前缀为spring.resources相关的进行绑定
拓展 : (配置类只有一个有参构造器 ,所有参数的值都会从容器中进行确定)
通过配置 add-mapping: false 就可以将所有的静态资源禁止访问