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幫助我們進行定製配置