SpringBoot学习总结(二)

一、配置文件

1.properties

2.yaml

YAML 是 “YAML Ain’t Markup Language”(YAML 不是一种标记语言)的递归缩写。

基本语法

  • key: value(kv之间有空格)
  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进不允许使用tab,只允许空格(idea中可以是tab,因为在解析时会把tab替换为空格
  • 缩进的空格数不重要,只要相同层级的元素左对齐即可
  • '#'表示注释
  • 字符串无需加引号,如果要加,’'与""表示字符串内容 会被 转义(例如:\n会翻译成字符)/不转义(例如:\n不会转义,还是表示换行符)

数据类型

1.字面量:单个的、不可再分的值。

k: v

2.对象 & 键值对的集合

#map、hash、set、object
行内写法:  k: {k1:v1,k2:v2,k3:v3}
#或
k: 
  k1: v1
  k2: v2
  k3: v3

3.数组:一组按次序排列的值

#array、list、queue
行内写法:  k: [v1,v2,v3]
#或者
k:
 - v1
 - v2
 - v3

二、功能分析

1.静态资源访问

静态资源目录
resources目录下的:

/static or 
/public or 
/resources or 
/META-INF/resources

请求静态资源的路径:当前项目根路径/ + 静态资源名

原理:静态映射/**
请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面。

修改默认的静态资源的路径

spring:
  web:
    resources:
      static-locations:
        [classpath:/index/]

# 请求时:回去/index目录下找静态资源

修改静态访问前缀(默认无前缀:

spring:
   mvc:
    static-path-pattern: /res/**

# 请求时的路径:当前项目根路径/res/ + 静态资源名

2.支持欢迎页

默认:静态资源路径下的index.html

  • 可以配置静态资源路径,设置欢迎页的位置
  • 但是不可以配置静态资源的访问前缀。否则导致 index.html不能被默认访问

3.自定义Favicon

即网页前的小图标。
将图片命名为favicon.ico,放在静态资源目录下即可。

同样不可以再设置静态资源访问前缀,否则会失效。

4.静态资源配置原理

SpringBoot启动默认加载自动配置类,其中SpringMVC功能的自动配置类 WebMvcAutoConfiguration生效。

@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 {}
//包含一个静态内部类
@Configuration(proxyBeanMethods = false)
//向容器中导入了EnableWebMvcConfiguration,这个类也是内部类
@Import(EnableWebMvcConfiguration.class)
//将配置文件的相关属性和xxxProperties进行了绑定。
//WebMvcProperties==>spring.mvc
//ResourceProperties==>spring.resources
//WebProperties==>spring.web
@EnableConfigurationProperties({ WebMvcProperties.class,
			org.springframework.boot.autoconfigure.web.ResourceProperties.class, WebProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {}
//只有一个有参构造器
//有参构造器所有参数的值都会从IOC容器中确定
//WebProperties webProperties;获取和spring.web绑定的所有的值的对象
//WebMvcProperties mvcProperties :获取和spring.mvc绑定的所有的值的对象
//ListableBeanFactory beanFactory:Spring的beanFactory
//HttpMessageConverters:找到所有的HttpMessageConverters
//ResourceHandlerRegistrationCustomizer:找到资源处理器的自定义器。
//DispatcherServletPath  
//ServletRegistrationBean:给应用注册Servlet、Filter....
public WebMvcAutoConfigurationAdapter(WebProperties webProperties, WebMvcProperties mvcProperties,
				ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider,
				ObjectProvider<ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider,
				ObjectProvider<DispatcherServletPath> dispatcherServletPath,
				ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {
			this.mvcProperties = mvcProperties;
			this.beanFactory = beanFactory;
			this.messageConvertersProvider = messageConvertersProvider;
			this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
			this.dispatcherServletPath = dispatcherServletPath;
			this.servletRegistrations = servletRegistrations;
			this.mvcProperties.checkConfiguration();
		}
//下面我们看EnableWebMvcConfiguration这个类
@Configuration(proxyBeanMethods = false)
	@EnableConfigurationProperties(WebProperties.class)
	public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {}
//它的addResourceHandlers方法
//定义了静态资源处理的默认规则(/**
@Override
		protected void addResourceHandlers(ResourceHandlerRegistry registry) {
			super.addResourceHandlers(registry);
			if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
			ServletContext servletContext = getServletContext();
			//这个方法定义了请求webjars下资源的规则
			addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");

			//这个方法定义了请求静态资源的规则
			//其实都一样,就是第二个参数(处理请求)和第三个参数

			//我们查看this.mvcProperties.getStaticPathPattern()得到的参数
			//默认就是private String staticPathPattern = "/**"(WebMvcProperties类中

			//第三个参数是一个Consumer接口,用来添加静态资源的路径
			//我们查看this.resourceProperties.getStaticLocations()
			// private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
			//private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
			//	"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
			//就是这里设置了静态资源的路径
			addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
				registration.addResourceLocations(this.resourceProperties.getStaticLocations());
				if (servletContext != null) {
					registration.addResourceLocations(new ServletContextResource(servletContext, SERVLET_LOCATION));
				}
			});
		}
//调用了本类中多个重载的addResourceHandler方法
//就是下面这个
private void addResourceHandler(ResourceHandlerRegistry registry, String pattern,
				Consumer<ResourceHandlerRegistration> customizer) {
			if (registry.hasMappingForPattern(pattern)) {
				return;
			}
			ResourceHandlerRegistration registration = registry.addResourceHandler(pattern);
			customizer.accept(registration);
			registration.setCachePeriod(getSeconds(this.resourceProperties.getCache().getPeriod()));
			registration.setCacheControl(this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl());
			customizeResourceHandlerRegistration(registration);
		}
#禁用所有静态资源规则
spring:
  web:
    resources:
      add-mappings: false
//下面介绍欢迎页的处理规则
//这个类中还有一个方法,定义了欢迎页请求规则
@Bean
		public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
				FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
			WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
					new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
					this.mvcProperties.getStaticPathPattern());
			welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
			welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
			return welcomePageHandlerMapping;
		}
//这个方法返回welcomePageHandlerMappingduixiang,我们查看他的构造方法
WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
			ApplicationContext applicationContext, Resource welcomePage, String staticPathPattern) {
		//可以看到有这个判断条件"/**".equals(staticPathPattern)
		//staticPathPattern是之前提到的WebMvcProperties中的属性,默认是/**
		//如果我们在配置文件中重新配置了,那么不相等返回false,就不能够forward转发
		if (welcomePage != null && "/**".equals(staticPathPattern)) {
			logger.info("Adding welcome page: " + welcomePage);
			setRootViewName("forward:index.html");
		}
		//这个if块判断是否有/index请求
		//调用Controller处理/index
		else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
			logger.info("Adding welcome page template: index");
			setRootViewName("index");
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值