同以前的 properties 用法
YAML 是 “YAML Ain’t Markup Language”(YAML 不是一种标记语言)的递归缩写。在开发这种语言时,YAML 的意思其实是:“Yet Another Markup Language”(仍是一种标记语言)
非常适合用来做以数据为中序的配置文件。
在 IDEA 中 xxx.yaml 也可以直接写为 xxx.yml
"zhangsan \n 李四"
'zhangsan \n 李四'
k: v
行内写法:k: {k1:v1,k2:v2,k3:v3}
# 或
k:
k1: v1
k2: v2
k3: v3
行内写法:k: [v1,v2,v3]
# 或者
k:
- v1
- v2
- v3
person:
name: zhangsan
boss: true
age: 21
birthdate: 2022/12/9
interests:
- 篮球
- 足球
- 羽毛球
- 数字18
animal: [猫,狗]
score:
english: 80
math: 90
salarys: [8822,1290]
pet:
name: 旺旺
weight: 99.1
allpets:
sick:
- {name: 小蓝,weight: 92}
- name: 小红
weight: 80
- name: 小黑
weight: 89
health: [{name: 小花,weight:90},{name: 小白,weight: 88}]
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!--######################### 插件 ###############################-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<!-- 在打包时,防止 SpringBoot 加载过多的类 -->
<configuration>
<excludes>
<exclude>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
SpringBoot 的自动配置基于 SpringMVC ,所以大多数场景我们都无需自定义配置
SpringBoot 的自动化配置包括了以下这些默认配置:
Converter
,GenerIcConverter
,Formatter
HttpMessageConverters
MessageCodeResolver
(国际化用)index.html
页支持ConfigurableWebBindingInitializer
(DataBinder 负责将请求数据绑定到 JavaBean 上)如果想要自动化配置,那么 SpringBoot 官方也给出了以下几样建议
@EnableWebMvc
注解。使用 @Configuraion + @WebMvcConfigurer
自定义规则WebMvcRegistrations
改变默认底层组件@EnableWebMvc+@Configuration+DelegatingWebMvcConfiguration
全面接管 SpringMVC
只要静态资源放在类路径下: /static
(or public
or /resources
or META-INF/resources
)
访问:当前项目根路径/ + 静态资源路径
**原理:**静态映射 /**
。
请求进来,先去找 Controller 看能不能处理。
改变默认的静态资源路径:
spring:
resources:
static-locations: [ classpath: /haha/]
默认无前缀
spring:
mvc:
static-path-pattern: /res/**
经过设置后,变成了:当前项目 + static-path-pattern + 静态资源名 = 静态资源文件夹下查找
例子:
springboot 支持 webjar;
WebJars 是打包成 JAR(Java Archive)文件的客户端Web库(例如jQuery和Bootstrap)。
官网:WebJars - Web Libraries in Jars
直接复制官网中的坐标粘贴至项目的 pom.xml 即可。
<dependency>
<groupId>org.webjars.npm</groupId>
<artifactId>jquery</artifactId>
<version>3.6.0</version>
</dependency>
如果要访问 webjar 为我们提供的 jar 包,那么访问需要加上前缀 webjar 再访问 webjar 中的插件
示例:/webjars/jquery/3.6.0/dist/jquery.js,后面地址要按照依赖的包路径填写
Favicon
跟欢迎页一样,不可以配置静态资源的访问前缀,否则会导致自定义图标失效
**使用:**将 favicon.ico 图标放在静态资源目录下即可。名称不可变
@AutoConfiguration(
after = {DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class}
)
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
public class WebMvcAutoConfiguration {}
@Configuration(
proxyBeanMethods = false
)
@Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class})
@EnableConfigurationProperties({WebMvcProperties.class, WebProperties.class})
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ServletContextAware {}
public WebMvcAutoConfigurationAdapter(WebProperties webProperties, WebMvcProperties mvcProperties, ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider, ObjectProvider<WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider, ObjectProvider<DispatcherServletPath> dispatcherServletPath, ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {
this.resourceProperties = webProperties.getResources();
this.mvcProperties = mvcProperties;
this.beanFactory = beanFactory;
this.messageConvertersProvider = messageConvertersProvider;
this.resourceHandlerRegistrationCustomizer = (WebMvcAutoConfiguration.ResourceHandlerRegistrationCustomizer)resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
this.dispatcherServletPath = dispatcherServletPath;
this.servletRegistrations = servletRegistrations;
this.mvcProperties.checkConfiguration();
}
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 获取静态资源的 add-mappings 属性,如果为false,那么所有的静态资源都被禁用了
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
// 配置 webjars 的默认路径
this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
// 配置 静态资源 的访问路径
this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (this.servletContext != null) {
ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
registration.addResourceLocations(new Resource[]{resource});
}
});
}
}
我们可以配置 resouce 中的 add-mappings 属性,如果值是 false ,静态资源都将不可访问
spring:
web:
resources:
add-mappings: false
默认 静态资源 的配置路径
public static class Resources {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
private String[] staticLocations;
private boolean addMappings;
private boolean customized;
private final WebProperties.Resources.Chain chain;
private final WebProperties.Resources.Cache cache;
public Resources() {
this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
this.addMappings = true;
this.customized = false;
this.chain = new WebProperties.Resources.Chain();
this.cache = new WebProperties.Resources.Cache();
}
public String[] getStaticLocations() {
// 返回默认路径
return this.staticLocations;
}
// HandlerMapping:处理映射,保存了每一个 Handler 能处理哪些请求
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations());
return welcomePageHandlerMapping;
}
// ###################### 构造器 ########################
WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders, ApplicationContext applicationContext, Resource welcomePage, String staticPathPattern) {
// 要用欢迎页功能,路径必须是 /**
if (welcomePage != null && "/**".equals(staticPathPattern)) {
logger.info("Adding welcome page: " + welcomePage);
this.setRootViewName("forward:index.html");
} else if (this.welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
//调用 Controller /index
logger.info("Adding welcome page template: index");
this.setRootViewName("index");
}
}
与欢迎页面一样,默认是 /**
,如果没有将会在控制器中找 /favicon.ico
路径