Ⅰ所踊、簡介
如何使用SpringBoot;
1)概荷、創(chuàng)建SpringBoot應用,選中我們需要的模塊碌燕;
2)误证、SpringBoot已經(jīng)默認將這些場景配置好了,只需要在配置文件中指定少量配置就可以運行起來
3)修壕、自己編寫業(yè)務代碼愈捅;
自動配置原理?
每當我們在創(chuàng)建項目中新增了一個模塊場景時慈鸠,我們都要考慮這個場景SpringBoot幫我們配置了什么蓝谨?我們能不能修改?我們能修改哪些配置青团?我們能不能擴展譬巫?
怎么看spring幫我們配置了什么:
項目的External Libraries中有一個自動配置包,這個包下有很多的自動配置模塊:
每個模塊中會有對應的自動配置類:
xxxxAutoConfiguration:幫我們給容器中自動配置組件督笆;
xxxxProperties:配置類來封裝配置文件的內(nèi)容芦昔;
我們需要參考這個配置類,就能知道springboot幫我們自動配置了什么
Ⅱ娃肿、springboot對靜態(tài)資源的映射
springboot中org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
類定義了一些靜態(tài)資源的默認配置咕缎,類的部分代碼如下:
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware {
//可以設置和靜態(tài)資源有關的參數(shù),緩存時間等
WebMvcAuotConfiguration:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Integer cachePeriod = this.resourceProperties.getCachePeriod();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(
registry.addResourceHandler("/webjars/**")
.addResourceLocations(
"classpath:/META-INF/resources/webjars/")
.setCachePeriod(cachePeriod));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
//靜態(tài)資源文件夾映射
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(
registry.addResourceHandler(staticPathPattern)
.addResourceLocations(
this.resourceProperties.getStaticLocations())
.setCachePeriod(cachePeriod));
}
}
//配置歡迎頁映射
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(
ResourceProperties resourceProperties) {
return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),
this.mvcProperties.getStaticPathPattern());
}
//配置喜歡的圖標
@Configuration
@ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
public static class FaviconConfiguration {
private final ResourceProperties resourceProperties;
public FaviconConfiguration(ResourceProperties resourceProperties) {
this.resourceProperties = resourceProperties;
}
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
//所有 **/favicon.ico
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
faviconRequestHandler()));
return mapping;
}
@Bean
public ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
requestHandler
.setLocations(this.resourceProperties.getFaviconLocations());
return requestHandler;
}
}
1)料扰、所有 /webjars/** 凭豪,都去 classpath:/META-INF/resources/webjars/ 找資源;
webjars:以jar包的方式引入靜態(tài)資源晒杈;參考:http://www.webjars.org/
<!--引入jquery-webjar-->在訪問的時候只需要寫webjars下面資源的名稱即可
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
2)嫂伞、"/**" 訪問當前項目的任何資源,都去(靜態(tài)資源的文件夾)找映射
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":當前項目的根路徑
localhost:8080/abc === 去靜態(tài)資源文件夾里面找abc
3)、歡迎頁末早; 靜態(tài)資源文件夾下的所有index.html頁面烟馅;被"/**"映射;
localhost:8080/ 找index頁面
4)然磷、所有的 **/favicon.ico 都是在靜態(tài)資源文件下找;
如何更改默認的資源文件路徑:
#更改默認配置靜態(tài)文件訪問路徑,如改為:類路徑下的hello文件夾郑趁,
spring.resources.static-locations=classpath:/test/
#多個路徑,逗號分隔:
spring.resources.static-locations=classpath:/test/姿搜,classpath:/test2/寡润,
Ⅲ、模板引擎
市面上的模板引擎大概有:JSP舅柜、Velocity梭纹、Freemarker、Thymeleaf
SpringBoot推薦的Thymeleaf致份;語法更簡單变抽,功能更強大;thymeleaf官網(wǎng)
1).引入thymeleaf氮块;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--不需要手動導入绍载,創(chuàng)建項目時選擇模塊那一步可以勾選idea會自動導入-->
2).thymeleaf的使用;
/**
*thymeleaf自動配置類的一小部分代碼
*/
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
//規(guī)定了要thymeleaf所在的文件路徑前綴是classpath:/templates/
public static final String DEFAULT_PREFIX = "classpath:/templates/";
//規(guī)定了thymeleaf所在文件的后綴名是 .html
public static final String DEFAULT_SUFFIX = ".html";
//就是說只要我們把HTML頁面放在classpath:/templates/滔蝉,thymeleaf就能自動渲染击儡;
使用:
控制器層
package com.byls.springboot;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
@Controller
public class HelloController {
@RequestMapping(value = "succeed")
public String helloController(Map<String, String > map){
map.put("hello","你好");
return "index";
}
}
頁面
<!DOCTYPE html>
<!--導入命名空間-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--${hello}直接取值,注意要卸載標簽的屬性中-->
<div th:text="${hello}">
直接訪問
</div>
</body>
</html>
值得注意的是蝠引,當通過瀏覽器的導航欄阳谍,請求地址訪問頁面時,頁面會顯示的是控制器預設的值螃概,如果將該html文件復制到桌面直接訪問矫夯,頁面的返回值則是div中的“直接訪問”
3).語法規(guī)則
官方文檔傳送門
1、th:text吊洼;改變當前元素里面的文本內(nèi)容茧痒;th:任意html屬性;來替換原生屬性的值
2.表達式:
Simple expressions:(表達式語法)
Variable Expressions: ${...}:獲取變量值融蹂;OGNL旺订;
Selection Variable Expressions: *{...}:選擇表達式:和${}在功能上是一樣;
Message Expressions: #{...}:獲取國際化內(nèi)容
Link URL Expressions: @{...}:定義URL超燃;
Fragment Expressions: ~{...}:片段引用表達式
Literals(字面量)
Text operations:(文本操作)
Arithmetic operations:(數(shù)學運算)
Boolean operations:(布爾運算)
Comparisons and equality:(比較運算)
Conditional operators:條件運算(三元運算符)
Special tokens:
No-Operation: _
Ⅳ区拳、springMVC的自動配置
1). Spring MVC auto-configuration
Spring Boot 自動配置好了SpringMVC
以下是SpringBoot對SpringMVC的默認配置:(WebMvcAutoConfiguration)
- Inclusion of
ContentNegotiatingViewResolver
andBeanNameViewResolver
beans. - 自動配置了ViewResolver(視圖解析器:根據(jù)方法的返回值得到視圖對象(View),視圖對象決定如何渲染(轉(zhuǎn)發(fā)意乓?重定向樱调?))
- ContentNegotiatingViewResolver:組合所有的視圖解析器的约素;
- 如何定制:我們可以自己給容器中添加一個視圖解析器;自動的將其組合進來笆凌;
- Support for serving static resources, including support for WebJars (see below).靜態(tài)資源文件夾路徑,webjars
- Static
index.html
support. 靜態(tài)首頁訪問 - Custom
Favicon
support (see below). favicon.ico
-
自動注冊了 of
Converter
,GenericConverter
,Formatter
beans.-
Converter
:轉(zhuǎn)換器圣猎; public String hello(User user):類型轉(zhuǎn)換使用Converter -
Formatter
格式化器; 2017.12.17===Date乞而;
-
@Bean
@ConditionalOnProperty(prefix = "spring.mvc", name = "date-format")//在文件中配置日期格式化的規(guī)則
public Formatter<Date> dateFormatter() {
return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化組件
}
? 自己添加的格式化器轉(zhuǎn)換器送悔,我們只需要放在容器中即可
- Support for
HttpMessageConverters
(see below). -
HttpMessageConverter
:SpringMVC用來轉(zhuǎn)換Http請求和響應的;User---Json爪模; -
HttpMessageConverters
是從容器中確定欠啤;獲取所有的HttpMessageConverter;
自己給容器中添加HttpMessageConverter屋灌,只需要將自己的組件注冊容器中(@Bean,@Component) - Automatic registration of
MessageCodesResolver
(see below).定義錯誤代碼生成規(guī)則 - Automatic use of a
ConfigurableWebBindingInitializer
bean (see below).
我們可以配置一個ConfigurableWebBindingInitializer來替換默認的洁段;(添加到容器)初始化WebDataBinder; 請求數(shù)據(jù)=====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
.
2).如何擴展SpringMVC
編寫一個配置類(@Configuration),是WebMvcConfigurerAdapter類型除嘹;不能標注@EnableWebMvc;既保留了所有的自動配置写半,也能用我們擴展的配置;
@Configuration
// WebMvcConfigurerAdapter過時,使用WebMvcConfigurer接口
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 瀏覽器發(fā)送 /cuzz 請求來到 success
registry.addViewController("/cuzz").setViewName("success");
}
}
原理:
1憾赁、WebMvcAutoConfiguration是SpringMVC的自動配置類
2、在做其他自動配置時會導入散吵;@Import(EnableWebMvcConfiguration.class)
@Configuration
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
//從容器中獲取所有的WebMvcConfigurer
@Autowired(required = false)
public void setConfigurers(List<WebMvcConfigurer> configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
//一個參考實現(xiàn)龙考;將所有的WebMvcConfigurer相關配置都來一起調(diào)用;
@Override
// public void addViewControllers(ViewControllerRegistry registry) {
// for (WebMvcConfigurer delegate : this.delegates) {
// delegate.addViewControllers(registry);
// }
}
}
}
3矾睦、容器中所有的WebMvcConfigurer都會一起起作用晦款;
4、我們的配置類也會被調(diào)用枚冗;
效果:SpringMVC的自動配置和我們的擴展配置都會起作用缓溅;
3).全面接管SpringMVC;
SpringBoot對SpringMVC的自動配置不需要了赁温,所有都是我們自己配置坛怪;所有的SpringMVC的自動配置都失效了
我們需要在配置類中添加@EnableWebMvc即可;
Ⅴ股囊、如何修改spring的自動配置
模式:
? 1)袜匿、SpringBoot在自動配置很多組件的時候,先看容器中有沒有用戶自己配置的(@Bean稚疹、@Component)如果有就用用戶配置的居灯,如果沒有,才自動配置;如果有些組件可以有多個(ViewResolver)將用戶配置的和自己默認的組合起來怪嫌;
? 2)义锥、在SpringBoot中會有非常多的xxxConfigurer幫助我們進行擴展配置
? 3)、在SpringBoot中會有很多的xxxCustomizer幫助我們進行定制配置
Ⅵ岩灭、RestfulCRUD
1)拌倍、默認訪問首頁
2)、國際化
3)川背、登陸