1.简介
使用SpringBoot:
(1)创建SpringBoot应用,选中我们需要的模块;
(2)SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来;
(3)自家编写业务代码
从上面可以知道SpringBoot帮我们自动配置好,那么这个自动配置原理:这个场景SpringBoot帮我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?
xxxxAutoConfiguration:帮我们给容器中自动配置组件;
xxxxProperties:配置类来封装配置文件的内容;
2.SpringBoot对静态资源的映射规则
使用 IntelliJ IDEA 中的 Spring Boot 初始化工具创建的项目,默认都会存在 resources/static 目录,很多小伙伴也知道静态资源只要放到这个目录下,就可以直接访问,除了这里还有没有其他可以放静态资源的位置呢?为什么放在这里就能直接访问了呢?这就是本节要讨论的内容了。
2.1 源码(webjars)
这个是SpringBoot自动配置的WebMvcAutoConfiguration类来帮我们干的。
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
....
}
所有的/webjars/**,都去classpath:/META-INF/resource/webjars/找资源(webjars,以jar包的方式引入静态资源)。
什么是webjars?就是以jar包的方式引入静态资源。官网地址:http://www.webjars.org/。类似于maven仓库。
2.2 源码(静态资源目录,和上面一个方法)
//addResourceHandlers:
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
继续追溯源码:mvcProperties.getStaticPathPattern(),这个到了WebMvcProperties类中:
public String getStaticPathPattern() {
return this.staticPathPattern;
}
//查看staticPathPattern
private String staticPathPattern = "/**";
继续追溯源码resourceProperties.getStaticLocations(),这个到了ResourceProperties类中:
public String[] getStaticLocations() {
return this.staticLocations;
}
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" };
/**访问当前项目的任何资源,都去(静态资源的文件夹)找映射,优先级从上到下
classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
/:当前项目的根路径
localhost:8080/abc===>去静态资源文件夹里面找abc
2.3 源码(默认首页)
@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;
}
追溯到getWelcomePage源码:
private Optional<Resource> getWelcomePage() {
String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
}
这个getStaticLocation和上面是一样的。上述代码翻译出来:
return new WelcomePageHandlerMapping(
"classpath:/META-INF/resources/index.html",
"classpath:/resources/index.html",
"classpath:/static/index.html",
"classpath:/public/index.html",
"/index.html"
, "/**");
默认首页:静态资源文件夹下的所有的index.html页面,被/**映射。
一句话概括:WebAutoConfiguration类自动为我们注册了如下文件为默认首页。
classpath:/META-INF/resources/index.html
classpath:/resources/index.html
classpath:/static/index.html
classpath:/public/index.html
/index.html
3.模板引擎
JSP、Velocity、Freemarker、Thymeleaf
SpringBoot推荐Thymeleaf,语法更简单,功能更强大。
3.1 引入Thymeleaf
在pom.xml文件中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.2 Thymeleaf的使用
3.2.1 源码
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
只需要把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染。
3.2.2 使用步骤
1.在HTML页面导入thymeleaf的名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
2.使用thymeleaf的语法
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF‐8">
<title>Title</title>
</head>
<body>
<h1>成功!</h1>
<!‐‐th:text 将div里面的文本内容设置为 ‐‐>
<div th:text="${hello}">这是显示欢迎信息</div>
</body>
</html>
3.3 Thymeleaf的语法规则
(1)th:text 改变当前元素的文本内容
th:任意html属性,来替换原生属性的值。
(2)表达式
Simple expressions:(表达式语法)
Variable Expressions: ${...}:获取变量值;OGNL;
1)、获取对象的属性、调用方法
2)、使用内置的基本对象:
#ctx : the context object.
#vars: the context variables.
#locale : the context locale.
#request : (only in Web Contexts) the HttpServletRequest object.
#response : (only in Web Contexts) the HttpServletResponse object.
#session : (only in Web Contexts) the HttpSession object.
#servletContext : (only in Web Contexts) the ServletContext object.
${session.foo}
3)、内置的一些工具对象:
#execInfo : information about the template being processed.
#messages : methods for obtaining externalized messages inside variables expressions, in the
same way as they would be obtained using #{…} syntax.
#uris : methods for escaping parts of URLs/URIs
#conversions : methods for executing the configured conversion service (if any).
#dates : methods for java.util.Date objects: formatting, component extraction, etc.
#calendars : analogous to #dates , but for java.util.Calendar objects.
#numbers : methods for formatting numeric objects.
#strings : methods for String objects: contains, startsWith, prepending/appending, etc.
#objects : methods for objects in general.
#bools : methods for boolean evaluation.
#arrays : methods for arrays.
#lists : methods for lists.
#sets : methods for sets.
#maps : methods for maps.
#aggregates : methods for creating aggregates on arrays or collections.
#ids : methods for dealing with id attributes that might be repeated (for example, as a
result of an iteration).
Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
补充:配合 th:object="${session.user}:
<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>
Message Expressions: #{...}:获取国际化内容
Link URL Expressions: @{...}:定义URL;
@{/order/process(execId=${execId},execType='FAST')}
Fragment Expressions: ~{...}:片段引用表达式
<div th:insert="~{commons :: main}">...</div>
Literals(字面量)
Text literals: 'one text' , 'Another one!' ,…
Number literals: 0 , 34 , 3.0 , 12.3 ,…
Boolean literals: true , false
Null literal: null
Literal tokens: one , sometext , main ,…
Text operations:(文本操作)
String concatenation: +
Literal substitutions: |The name is ${name}|
Arithmetic operations:(数学运算)
Binary operators: + , ‐ , * , / , %
Minus sign (unary operator): ‐
Boolean operations:(布尔运算)
Binary operators: and , or
Boolean negation (unary operator): ! , not
Comparisons and equality:(比较运算)
Comparators: > , < , >= , <= ( gt , lt , ge , le )
Equality operators: == , != ( eq , ne )
Conditional operators:条件运算(三元运算符)
If‐then: (if) ? (then)
If‐then‐else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
Special tokens:
No‐Operation: _
4.SpringMVC自动配置
4.1 Spring MVC auto-configuration
SpringBoot自动配置好了SpringMVC。
以下是SpringBoot对SpringMVC的默认配置(WebMvcAutoConfiguration):
-
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
(1)自动配置了ViewResolver(视图解析器:根据方法的返回值得到了视图对象(View),视图对象决定如何渲染(转发,重定向))
(2)ContentNegotiatingViewResolver :组合所有的视图解析器的。
(3)如何定制?我们可以给容器中添加一个视图解析器;自动将其组合起来。
- Support for serving static resources, including support for WebJars (see below).静态资源文件夹路 径,webjars
- Static index.html support. 静态首页访问
- 自动注册了 of Converter , GenericConverter , Formatter beans.
(1)Conveter :转换器;public String hello(User user):类型转换使用Converter
(2)Formatter:格式转换器
(3)自己添加的格式转换器,只需要放在容器中
- Support for HttpMessageConverters (see below).
(1)HttpMessageConveters:SpringMVC用来转换Http请求和响应的;User->Json
(2)HttpMessageConveters是从容器中确定;获取所有的HttpMessageConveter;
(3)自己给容器中添加HttpMessageConveter,只需要将自己的组件注册容器中的(@Bean,@Component)
- Automatic registration of MessageCodesResolver (see below).定义错误代码生成规则
- Automatic use of a ConfigurableWebBindingInitializer bean (see below).
(1)可以配置一个ConfigurableWebBindingInitializer来替换默认的(添加到容器)
1)初始化WebDataBinder
2)请求数据======JavaBean
org.springframework.boot.autoconfigure.web:web的所有自动场景;
If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration
(interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type
WebMvcConfigurerAdapter , but without @EnableWebMvc . If you wish to provide custom instances of
RequestMappingHandlerMapping , RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver
you can declare a WebMvcRegistrationsAdapter instance providing such components.
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with
@EnableWebMvc .
4.2 扩展SpringMVC
看看之前SpringMVC的写法:
<mvc:view‐controller path="/hello" view‐name="success"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<bean></bean>
</mvc:interceptor>
</mvc:interceptors>
4.2.1 扩展方法
编写一个配置类(@Configuration),是WebMvcConfigurer类型,不能标注@EnableWebMvc。
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送test请求,会来到success页面
registry.addViewController("/test").setViewName("success");
}
}
4.2.2 扩展原理
(1)WebMvcAutoConfiguration是SpringMVC的自动配置类。
(2)在这个类中做其他配置时会导入,@Import(EnableWebMvcConfiguration.class)。点进去(这个类还在WebMvcAutoConfiguration)
@Configuration(proxyBeanMethods = false)
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {
private final ResourceProperties resourceProperties;
private final WebMvcProperties mvcProperties;
private final ListableBeanFactory beanFactory;
private final WebMvcRegistrations mvcRegistrations;
private ResourceLoader resourceLoader;
...
}
(3)容器中的所有WebMvcConfigurer都会一起起作用
(4)我们的配置类也会被调用
SpringMVC的自动配置和我们的扩展配置都会起作用。
4.3 全面接管SpringMVC
SpringBoot对SpringMVC自动配置不需要了,所以都是我们自己配置的,所有的SpringMVC的自动配置都失效了。
4.3.1 使用方法
我们需要在配置类中添加@EnableWebMvc即可。
//使用WebMvcConfigurer可以用来扩展SpringMVC的功能
//@EnableWebMvc全面接管SpringMVC
@EnableWebMvc
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送test请求,会来到success页面
registry.addViewController("/test").setViewName("success");
}
}
4.3.2 原理
为什么@EnableWebMvc自动配置就失效了?
(1)@EnableWebMvc的核心:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Import({DelegatingWebMvcConfiguration.class})
public @interface EnableWebMvc {
}
(2)点进去DelegatingWebMvcConfiguration,可以看到DelegatingWebMvcConfiguration继承了WebMvcConfigurationSupport:
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
public DelegatingWebMvcConfiguration() {
}
@Autowired(
required = false
)
public void setConfigurers(List<WebMvcConfigurer> configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
}
}
(3)查看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 {
...
}
(4)@EnableWebMvc将WebMbcConfigurationSupport组件导入进来。
(5)导入的WebMvcConfigurationSupport只是SpringMVC的最基本的功能。
5.如何修改SpringBoot的默认配置
(1)SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean,@Component),如果有就用用户配置的。如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来。
(2)在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置
(3)在SpringBoot中会有非常多的xxxCustomizer帮助我们进行定制配置