SpringBoot简介
使用SpringBoot
- 创建SpringBoot应用,选中我们需要的模块;
- SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
- 自己编写业务代码就可以了
自动配置原理
xxxxAutoConfiguration
:帮我们给容器中自动配置组件
xxxxProperties
:配置类,用来封装配置文件的内容;
SpringBoot对静态资源的映射规则
WebMvcAutoConfiguration类中有这么一段代码(IDEA中你可以按住ctrl+shift+alt+N来跳转到你想要查看的类):
//添加资源映射
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
}
跳转到ResourceProperties中:这个类可以设置和静态资源有关的参数,比如缓存时间等
@ConfigurationProperties(
prefix = "spring.resources",
ignoreUnknownFields = false
)
public class ResourceProperties {
所有 /webjars/**
,都去 classpath:/META-INF/resources/webjars/
找资源;
什么是webjars?点进去就知道了
webjars就是以jar包的方式引入静态资源;
选好版本号后把依赖粘贴复制进pom.xml就可以了
可以看到这个文件夹的路径跟上面那个添加资源映射的类说的一样:classpath:/META-INF/resources/webjars/
我们可以到浏览器中访问试一下:http://localhost:8080/webjars/jquery/3.3.1-1/jquery.js
如图所示是可以访问到的
/**
:访问当前项目的任何资源,只要没人处理,都会去(静态资源的文件夹下)找映射
静态资源的文件夹:
"classpath:/META‐INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":当前项目的根路径
例子,我们测试"classpath:/resources/"这个
然后我们就可以到浏览器中http://localhost:8080/asserts/js/Chart.min.js
访问了
如果要改变为我们自定义的路径,在配置文件中用spring.resources.static-locations
配置即可,多个路径用,
分隔
例子:
spring.resources.static-locations=classpath:/hello/,classpath:/nyh/
还有一个方法:welcomePageHandlerMapping
//配置首页的映射
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) {
return new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
}
意思是在静态资源文件夹下的所有index.html页面;会被/**
映射
比如你在浏览器输入localhost:8080/
,因为/
满足/**
,所以会找到index页面映射出来
还有就是页面的icon图标的配置
把图标放在在静态资源文件下SpringBoot就会自动找到它并配置好,图标名字要叫favicon.ico
以下是自动配置的代码
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(-2147483647);
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
return mapping;
}