springBoot初級入門
獲取配置文件中的值@ConfigurationProperties
1吼鱼、這個注解默認只能從全局配置文件中獲取信息蚪腐,全局配置有兩個箫津,如下:
1婿崭、application.properties
2俭嘁、application.yml
yml
1躺枕、key和value之間需要空格
2、縮進顯示層次關(guān)系供填,縮進多少無所謂拐云,只要左對齊那么就是一個層級關(guān)系的
3、key: value
:: 表示一個鍵值對近她,注意一定要有空格
4叉瘩、大小寫敏感
5、屬性的值如果是字符串可以直接寫粘捎,不需要加上雙引號或者單引號
1薇缅、雙引號:加上雙引號的值不會轉(zhuǎn)義里面的特殊字符,比如字符串中包含一個換行符攒磨,那么就會在輸出的時候換行
2泳桦、單引號:會轉(zhuǎn)義特殊的字符,會直接輸出換行符為`\n`
6娩缰、List和Set的表示方法:
# key與value之間空格
pets:
- dog
- pig
- cat
## 行內(nèi)的寫法:
pets: [dog,pig,cat]
7灸撰、Map<key,value>的寫法
map: {name: Jack,age: 22,gender: 女}
8、舉例
1拼坎、JavaBean:
/**
* ConfigurationProperties : 這個注解表示這個實體類的值來自于配置文件中浮毯,當然包括properties和yaml文件
* prefix表示這個配置文件中的前綴
*/
@Component //注入到容器中
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private int age;
private List<Object> list;
private Map<String,Object> map;
private User user;
private Date birthday;
}
2、application.yml
person:
name: 陳加兵
age: 22
list:
- zhangsan
- lisi
user:
name: 鄭元梅
age: 22
map: {name: Jack,age: 22,gender: 女}
birthday: 2012/12/11
3泰鸡、添加一個依賴债蓝,將會在配置文件中自動提示
<!--導(dǎo)入這個處理器,在配置文件中將會自動提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
4盛龄、測試類:
@RunWith(SpringRunner.class)
@SpringBootTest
public class TeammissionServerApplicationTests {
@Autowired
private Person person; //自動注入
@Test
public void contextLoads() {
System.out.println(person); //輸出配置信息
}
}
properties
1惦蚊、依然可以使用@ConfigurationProperties這個注解獲取配置文件的值器虾,不過和yml文件中的配置有很大的區(qū)別,如下:
person.age=22
person.name=陳加兵
person.birthday=2012/12/11
person.list=a,b,c
person.map.name=陳加兵
person.map.age=22
person.user.name=Jack
person.user.age=33
@Value
1蹦锋、這個注解是spring中的注解兆沙,用于獲取配置文件的值
使用方式 | 作用 |
---|---|
@Value("${}") | 獲取配置文件中的值 |
@Value("#{}") | 獲取配置文件中的值,不過需要使用<util:>這個指定id |
@Value("value") | 可以直接為變量賦值 |
2莉掂、不支持JSR303校驗
@PropertySource
1葛圃、我們在使用@configurationProperties獲取文件中的信息的時候,默認只能從默認的配置文件中獲取信息憎妙,如果我們需要自己單獨定義一個配置文件库正,那么需要使用@PropertySource這個注解獲取其中的信息
2、 我們在項目路徑下新建一個person.properties文件厘唾,其中的內(nèi)容如下:
person.age=22
person.name=陳加兵
person.birthday=2012/12/11
person.list=a,b,c
person.map.name=陳加兵
person.map.age=22
person.user.name=Jack
person.user.age=33
3褥符、在Person這個實體類中添加如下的注解配置,使用@PropertySource這個注解加載這個配置文件抚垃,如下:
/**
* ConfigurationProperties : 這個注解表示這個實體類的值來自于配置文件中喷楣,當然包括properties和yaml文件
* prefix表示這個配置文件中的前綴
*/
@PropertySource(value ={"classpath:person.properties"}) //從自定義的配置文件中獲取信息
@Component //注入到容器中
@ConfigurationProperties(prefix = "person") //獲取前綴為person的信息
public class Person {
private String name;
private int age;
private List<Object> list;
private Map<String,Object> map;
private User user;
private Date birthday;
}
4、使用@PropertySource這個注解能夠?qū)胱远x的配置文件并且獲取其中的值
5鹤树、 使用這個注解只能加載properties文件铣焊,無法加載YAML文件
@ImportSource
1、在springBoot中幾乎沒有配置文件罕伯,全部都是使用注解曲伊,那么我們?nèi)绻枰褂门渲梦募覀冊撊绾巫屵@個配置文件生效呢追他?
2坟募、我們可以使用這個注解加載自己的配置文件xml,不過在springBoot中不贊成這樣做邑狸,因為可以使用配置類來代替配置文件xml
3懈糯、我們在項目的resource文件下新建一個beans.xml,其中配置了如下的信息:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="com.telles.teammissionserver.bean.Person">
<property name="age" value="22"></property>
<property name="name" value="陳加兵"></property>
</bean>
</beans>
4推溃、我們現(xiàn)在需要將其加入到IOC容器中,必須使用@ImportSource這個注解届腐,我們需要在項目的主配置類上添加這個注解導(dǎo)入配置文件
//使用這個注解可以導(dǎo)入自定義的配置文件xml,其中的value值是一個數(shù)組铁坎,可以填寫多個值
@ImportResource(value = {"classpath:beans.xml"})
@SpringBootApplication
public class TeammissionServerApplication {
public static void main(String[] args) {
SpringApplication.run(TeammissionServerApplication.class, args);
}
}
配置類
1、我們在springBoot中已經(jīng)完全舍棄了配置文件的形式來為容器注入組件犁苏,我們都是使用配置類的形式硬萍,每個項目在建立的時候都有一個主配置類,使用SpringBootApplication
這個注解來標注的围详,我們也可以定義自己的配置類朴乖,只要使用@Configuration這個注解標注即表示當前類是一個配置類祖屏。
2、我們在新建一個包config專門存放配置類买羞,在其中可以建立多個配置類袁勺,如下:
@Configuration //指定這是一個配置類
public class MainConfig {
/**
* @Bean: 這個注解將其注入到IOC容器中
* 其中的返回類型Person就相當于class,方法名就是返回的id畜普,在IOC容器中我們可以使用這個id獲取自動
* 配置的實例
*/
@Bean
Person person(){
Person person=new Person();
person.setAge(22);
person.setName("chen");
return person;
}
}
配置文件占位符
1期丰、可以使用隨機數(shù),如下:
## 使用隨機的uuid為其復(fù)制
person.name=${random.uuid}
## 配置一個隨機的int
person.age=${random.int}
2吃挑、可以使用占位符獲取之前配置的值钝荡,如果沒有可以使用:
指定默認值
## 配置一個隨機的int
person.age=${random.int}
# 使用占位符獲取之前配置的值,如果這個值不存在舶衬,那么使用指定的默認值
person.user.age=${person.age:33}
多環(huán)境開發(fā)
1埠通、我們在開發(fā)的時候可能會面對多環(huán)境,比如生產(chǎn)環(huán)境逛犹,測試環(huán)境端辱,上線運行環(huán)境,針對這幾種不同的環(huán)境圾浅,我們可能需要的配置也是不相同的掠手,此時我們就需要在不同的環(huán)境之間切換不同的配置文件。
properties
1狸捕、我們可以在創(chuàng)建不同的properties文件喷鸽,文件名如:application-{profile}.properties
,比如灸拍,application-dev.properties
和application-prod.properties
這兩個文件做祝,此時我們可以springBoot的朱主配置文件中application.properties文件中添加如下的語句,用來激活某一種的配置文件:
# 激活dev配置文件鸡岗,那么此時springBoot就會以application-dev.properties文件為配置文件
spring.profiles.active=dev
yaml
1混槐、在yaml中不需要建立多個文件,因為yaml可以使用---
區(qū)分不同的文檔轩性,只要在一個主配置文件application.yml中添加不同區(qū)域的文檔声登,即使表示不同的文件,如下:
## 文檔塊1揣苏,此時激活dev
server:
port: 8081
spring:
profiles:
active: dev
---
## dev環(huán)境的配置
server:
port: 8080
spring:
profiles: dev
---
## prod環(huán)境的配置
server:
port: 8088
spring:
profiles: prod
配置文件加載位置
1悯嗓、springBoot項目創(chuàng)建的時候在classpath路徑下的有一個application.properties
文件,這個就是springBoot默認的文件位置卸察,但是我們還可以在其他的位置指定配置文件脯厨,依然會生效。
2坑质、springBoot有以下的位置可以放置配置文件合武,按照優(yōu)先級由高到低如下:
1临梗、項目路徑下的config文件夾中
2、直接放在項目路徑下
3稼跳、classpath路徑下的config文件夾中
4盟庞、直接放在classpath路徑下【創(chuàng)建項目的時候默認位置】
3、classpth即是resource文件夾下
4岂贩、注意:無論放在哪個位置茫经,默認加載的文件名稱必須是application.properties
5、如果高優(yōu)先級和低優(yōu)先級共有的配置萎津,那么高優(yōu)先級會覆蓋低優(yōu)先級的配置卸伞,但是高優(yōu)先級配置文件中的沒有的配置,如果在低優(yōu)先級的配置文件中存在锉屈,那么依然會生效荤傲,這樣就可以形成互補的形式
6、可以在默認的配置文件application.properties文件中使用spring.config.location
來指定外部的配置文件颈渊,如下:
spring.config.location=/usr/local/application.properties
7遂黍、在項目已經(jīng)發(fā)布出去之后,我們也可以使用命令行的方式指定配置文件的位置俊嗽,如:java -jar springboot.jar --spring.config.location=/usr/local/application.properties
日志框架
1雾家、spring默認的規(guī)定的日志框架是self4j和logback,這是目前的主流的日志框架绍豁,如果想要使用self4j和log4j芯咧,那么需要使用指定的適配類進行接口的轉(zhuǎn)換。轉(zhuǎn)換關(guān)系如下圖:
[圖片上傳失敗...(image-25c743-1538922709906)]
2竹揍、默認什么都不配置的情況下敬飒,日志是開啟的,使用的是self4j+logback芬位,日志的級別是info
3无拗、我們可以在全局配置文件appliction.properties或者application.yml中修改默認的配置,比如修改默認的日志級別昧碉,控制臺輸出格式英染,輸出的日志文件的位置
4、日志的輸出級別由高到低的級別如下:ERROR
, WARN
, INFO
, DEBUG
, or TRACE
.
5被饿、在springBoot中支持自定義的日志配置如下:
# 指定com.telles包下的所有類下的日志輸出級別為debug,可以指定某個類或者某個包下的類所使用的日志級別
logging.level.com.telles=error
# 如果指定的相對路徑四康,那么就是在當前項目下,如果指定的了絕對路徑锹漱,比如c:\\log\\spring.log箭养,那么就是在指定的位置上生成log輸出的文件
logging.file=log/spring.log
# 也是指定的日志的文件的位置慕嚷,不過是在當前項目的所在根目錄下指定的文件的位置哥牍,比如/log/spring.log毕泌,這個就是在該項目的根目錄中的log文件夾下指定的日志文件是spring.log
logging.path=/log/spring.log
# 指定控制臺輸出的格式,但是也是有默認的格式嗅辣,這個和log4j的配置是一樣的
logging.pattern.console=
# 指定日志文件的輸出格式
logging.pattern.file=
# 指定文件最大大小
logging.file.max-size=
# 指定日期的格式
logging.pattern.dateformat=
## 文件最大保存歷史量
logging.file.max-history=
6撼泛、當然也可以使用自定義的配置文件,但是命名有一定的規(guī)范澡谭,否則springBoot并不能自動識別愿题,比如如果使用logback日志框架的話,那么自定義的配置文件的名稱必須是logback-xxx.xml
,放在resource文件夾下,否則將不能識別蛙奖,基本的配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--定義日志文件的存儲地址 一般存儲在服務(wù)器的文件夾中-->
<property name="LOG_HOME" value="/tmp/logs" />
<!-- 控制臺輸出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化輸出-->
<pattern>[%p]-[%c] - %m%n</pattern>
</encoder>
</appender>
<!-- 按照每天生成日志文件 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件輸出的文件名,使用日期進行拼接-->
<FileNamePattern>${LOG_HOME}/web.log.%d{yyyy-MM-dd}.log</FileNamePattern>
<!--日志文件保留天數(shù)-->
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化輸出:%d表示日期潘酗,%thread表示線程名,%-5level:級別從左顯示5個字符寬度%msg:日志消息雁仲,%n是換行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<!--日志文件最大的大小-->
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>100MB</MaxFileSize>
</triggeringPolicy>
</appender>
<!-- show parameters for hibernate sql 專為 Hibernate 定制
<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE" />
<logger name="org.hibernate.type.descriptor.sql.BasicExtractor" level="DEBUG" />
<logger name="org.hibernate.SQL" level="DEBUG" />
<logger name="org.hibernate.engine.QueryParameters" level="DEBUG" />
<logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" />-->
<!--myibatis log configure-->
<logger name="com.apache.ibatis" level="DEBUG"/>
<logger name="java.sql.Connection" level="DEBUG"/>
<logger name="java.sql.Statement" level="DEBUG"/>
<logger name="java.sql.PreparedStatement" level="DEBUG"/>
<!-- 日志輸出級別 -->
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
<!--日志異步到數(shù)據(jù)庫 -->
<!--<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">-->
<!--<!–日志異步到數(shù)據(jù)庫 –>-->
<!--<connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">-->
<!--<!–連接池 –>-->
<!--<dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource">-->
<!--<driverClass>com.mysql.jdbc.Driver</driverClass>-->
<!--<url>jdbc:mysql://127.0.0.1:3306/databaseName</url>-->
<!--<user>root</user>-->
<!--<password>root</password>-->
<!--</dataSource>-->
<!--</connectionSource>-->
<!--</appender>-->
</configuration>
自定義日志文件
1仔夺、springboot啟動的時候會自動加載日志的配置文件,默認使用的是self4j+logback攒砖,雖然springBoot為我們自動配置了默認的配置缸兔,但是我們還是需要自己定義配置文件,我們可以創(chuàng)建一個配置文件放置在resuorce文件夾下面吹艇,但是命名規(guī)則確實有一些區(qū)別惰蜜,如下:
Logging System | Customization |
---|---|
Logback |
logback-spring.xml , logback-spring.groovy , logback.xml , or logback.groovy
|
Log4j2 |
log4j2-spring.xml or log4j2.xml
|
JDK (Java Util Logging) | logging.properties |
2、總結(jié)的說就是受神,如果使用logback的日志抛猖,那么可以指定一個logback.xml放置在resource文件夾下,那么springBoot將會默認加載這個配置路克,直接覆蓋默認的配置樟结。如果使用log4j這個日志框架,那么可以直接創(chuàng)建一個log4j.properties放置在resrouce文件夾下精算。如果使用log4j2這個日志瓢宦,我們可以使用log4j2.xml這個日志文件放置在resoruce文件夾下。
日志框架的切換
1灰羽、上面的日志文件都是一個配置文件針對多個環(huán)境驮履,但是如果我們想要使用profile的功能,比如開發(fā)環(huán)境使用一個日志配置文件廉嚼,運行環(huán)境使用另外一個配置文件玫镐,那么此時就需要使用日志框架的profile功能,此時的命名規(guī)則就必須是logback-{profile}.xml
怠噪,比如使用logback框架的時候恐似,那么我們可以配置logback-dev.xml作用與開發(fā)環(huán)境,使用logback-spring.xml用于運行環(huán)境傍念。
2矫夷、雖然懂得了命名規(guī)則葛闷,那么需要在日志的配置文件中指定切換語句,如下:
<springProfile name="staging">
<!-- configuration to be enabled when the "staging" profile is active -->
</springProfile>
<springProfile name="dev | staging">
<!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
</springProfile>
<springProfile name="!production">
<!-- configuration to be enabled when the "production" profile is not active -->
</springProfile>
程序中使用日志
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private final Logger logger= LoggerFactory.getLogger(this.getClass());
SpringMVC的開發(fā)
1双藕、如果想要開發(fā)springmvc模塊淑趾,只需要選中web模塊即可,默認的springBoot會自動為我們創(chuàng)建一些自動配置忧陪,不用自己一步一步的搭建springMVC框架扣泊。但是如果我們需要自己全面接管或者在原有的基礎(chǔ)上進行一些擴展的話,SpringBoot都提供了一些支持嘶摊。
創(chuàng)建一個web模塊
1延蟹、創(chuàng)建項目,導(dǎo)入啟動器叶堆,如下:
<!--導(dǎo)入web模塊-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--springBoot的測試模塊-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--導(dǎo)入這個處理器等孵,在配置文件中將會自動提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!--熱啟動,保證每次修改蹂空,程序都會自動更新-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
引入靜態(tài)資源
webjars的引入
1俯萌、springMVC引入自動配置資源都是在org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration這個類中進行配置,因此靜態(tài)資源位置的映射也是在這個類中完成的上枕,如下咐熙,即是配置靜態(tài)資源映射的方法
@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();
//請求/webjars/**
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry
.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod))
.setCacheControl(cacheControl));
}
//添加 /**資源映射
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(
registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(
this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod))
.setCacheControl(cacheControl));
}
}
2、通過上面的代碼可以知道任何/webjars/**
這種請求的方式都會在classpath:/META-INF/resources/webjars/
這個位置查找相關(guān)的靜態(tài)資源
3辨萍、webjars:是一種以jar包的方式引入靜態(tài)資源棋恼,比如引用jQuery、Bootstrap的文件锈玉,那么我們只需要引入對應(yīng)的jar包即可訪問這些靜態(tài)資源爪飘,官方網(wǎng)址:https://www.webjars.org/
4、比如我們現(xiàn)在引入jquery的jar拉背,如下:
<!--引入jquery的jar-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1-1</version>
</dependency>
5师崎、此時我們看到導(dǎo)入webjas的目錄結(jié)構(gòu),如下椅棺,自動配置的資源映射就是對應(yīng)webjars下的資源位置犁罩,
1)、此時如果想要獲取jquery.js這個文件,那么可以通過`http://localhost:8080/webjars/jquery/3.3.1-1/jquery.js`這個url查詢到指定的文件,這個就是相對于上面springBoot自動配置的webjars的映射位置
其他靜態(tài)資源的引入
1伙窃、除了映入webjars這個靜態(tài)資源,我們還有自定義的css和js文件仍秤,那么我們也必須有一個位置放置這些資源,讓springBoot能夠訪問到
2嫩海、/**
是用來訪問當前項目的任何資源早抠,主要的就是靜態(tài)文件夾递胧,默認映射的位置如下:
1)鸦做、classpath : 指定的是java和resources文件夾
2)、這寫文件夾都是存放靜態(tài)資源的谓着,那么肯定會發(fā)生沖突,比如多個文件夾存放的靜態(tài)資源名稱是一樣的坛掠,那么我們該如何查找呢赊锚?
3)、這些文件夾是否順序訪問的屉栓,即是按照如下的優(yōu)先級進行訪問的舷蒲,如果上一級找到了,那么將會返回友多,下面的文件夾將不會查找
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
3牲平、我們可以在classpath路徑下創(chuàng)建上面的四個文件夾用來存放靜態(tài)資源文件夾,這樣我們就可以訪問到這些資源了域滥。如下:
4纵柿、此時我將slider.css
這個靜態(tài)資源文件放置到static中,那么我們可以通過請求http://localhost:8080/slider.css
启绰,將可以訪問到這個資源昂儒,主要就是去上面的四個文件夾下查找文件,如果有這個文件委可,那么就返回即可渊跋。
配置首頁
1、在springBoot中着倾,首頁也為我們自動配置了存放的位置
2拾酝、我們只需把首頁index.html
放置在靜態(tài)資源文件夾下即可訪問,比如我們放一個index.html在static文件夾下卡者,直接訪問http://localhost:8080/
這個即可自動跳轉(zhuǎn)首頁
配置小圖標
1蒿囤、我們可以放置一個favicon.ico
圖片在靜態(tài)資源文件夾下,那么即可自動為我們的頁面配置上小圖標
自定義靜態(tài)資源存放位置
1崇决、我們在全局配置文件中指定自己配置的資源存放位置蟋软,如下:
spring.resources.static-locations=classpath:/myStatic
2、一旦配置這個路徑嗽桩,那么上面springBoot自動配置的路徑將會失效
模板引擎
1岳守、sprintBoot不支持jsp,但是支持thymeleaf模板引擎碌冶,我們可以導(dǎo)入這個模板引擎
<!--引入themleaf模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2湿痢、我們不需要指定版本號,在springBoot中已經(jīng)為我們指定了默認的版本號,如下:
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<thymeleaf-extras-data-attribute.version>2.0.1</thymeleaf-extras-data-attribute.version>
<thymeleaf-extras-java8time.version>3.0.1.RELEASE</thymeleaf-extras-java8time.version>
<thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
<thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
使用thymelefa
1譬重、我們只需要將所有的html文件放在teamplate下拒逮,那么thymeleaf將會自動解析其中的文件
2、引入下面的約束將會自動提示語法:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
語法
1臀规、th
: 這個是使用th任意屬性來替換原生屬性滩援,比如替換id使用th:id
,class使用th:class
2、<h1 th:text="${hello}">成功訪問</h1>
:替換標簽體內(nèi)的文本
3塔嬉、表達式:
Simple expressions:
Variable Expressions: ${...}
Selection Variable Expressions: *{...}
Message Expressions: #{...}
Link URL Expressions: @{...}
Fragment Expressions: ~{...}
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:
Page 17 of 106No-Operation: _
springMVC的擴展
1玩徊、在springBoot中依賴mvc的自動配置肯定是不夠的,比如我們需要添加一個攔截器谨究,那么肯定是需要自己配置的恩袱,此時我們就需要定義自己的配置類進行擴展功能。
2胶哲、擴展的意思是幾保留了mvc的自動配置畔塔,也使用了一些自定義的功能。
3鸯屿、自動擴展的實現(xiàn):
1)澈吨、定義一個配置類,使用`@Configuration`
2)寄摆、繼承`WebMvcConfigurationSupport`棚辽,這個類是一個抽象類,其中有實現(xiàn)springmvc的不同組件冰肴,如果需要那個組件屈藐,只需要實現(xiàn)其中的方法即可
3)、在這個類中實現(xiàn)其中的方法即可熙尉。
4联逻、比如我們需要實現(xiàn)一個攔截器,那么我們需要創(chuàng)建一個攔截器類检痰,如下:
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("使用攔截器");
return true;
}
}
5包归、我們需要在配置類中配置這個攔截器,如下:
@Configuration //springBoot的自動配置類
public class MyConfig extends WebMvcConfigurationSupport {
//添加一個映射視圖的組件铅歼,每次請求helloWorld都會映射到index.html
@Override
protected void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/helloWorld").setViewName("index");
}
//添加一個攔截器
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/helloWorld");
}
}
全面接管SpringMVC
1公壤、全面接管的意思就是不需要springBoot的自動配置,而是全部使用自定義的配置
2椎椰、要實現(xiàn)全面接管springMVC厦幅,那么只需要在上面的配置上添加一個@EnableWebMvc
,如下:
@Configuration //springBoot的自動配置類
@EnableWebMvc //全面接管springMVC
public class MyConfig extends WebMvcConfigurationSupport {
}
指定日期格式
1慨飘、springBoot默認的可以轉(zhuǎn)換的日期格式:yyyy/MM/dd
确憨,那么我們可以在配置文件中改變這種配置格式译荞,如下:
## 指定日期格式
spring.mvc.date-format=yyyy-MM-dd
2、一旦轉(zhuǎn)換了這種日期的格式休弃,那么當用戶輸入的日期格式為上面的那種才會自動轉(zhuǎn)換成Date類型的數(shù)據(jù)吞歼,否則將會轉(zhuǎn)換失敗,出現(xiàn)異常
定制錯誤頁面
修改Tomcat的默認配置
1塔猾、在springBoot默認使用的是嵌入式的tomcat容器篙骡,我們可以在全局配置文件中修改默認的tomcat的配置。
2丈甸、如何修改tomcat 的默認配置糯俗?
1)、在全局的配置文件application.properties中修改配置即可老虫,如下:
1)、這些配置全部都是對應(yīng)著`org.springframework.boot.autoconfigure.web.ServerProperties`這個類茫多,Tomcat的配置對應(yīng)著`org.springframework.boot.autoconfigure.web.ServerProperties.Tomcat`
## 指定編碼格式
## 如果需要修改tomcat的默認配置祈匙,我們需要修改server.tomcat.xxx
server.tomcat.uri-encoding=utf-8
## 指定端口號
## 如果需要修改server的默配置,我們需要修改server.xxxx
server.port=8080
注冊Servlet天揖、Filter夺欲、Listener
1、在springBoot中如果需要用到Servlet今膊、過濾器和監(jiān)聽器些阅,那么就需要自己配置
2、配置三大組件對應(yīng)的類為:ServletRegistrationBean
斑唬、FilterRegistrationBean
市埋、ServletListenerRegistrationBean
。我們只需要在自定義的配置類中將三個組件注冊到容器中即可
3恕刘、完成注冊三大組件
1)缤谎、創(chuàng)建自己的三大組件
2)、創(chuàng)建一個配置類褐着,在其中創(chuàng)建注入三大組件即可坷澡,如下:
@Configuration //指定這是一個配置類
public class MyWebConfig {
//注冊自己的Servlet,在其中可以設(shè)置在配置文件中能夠設(shè)置的值
@Bean //將這個組件添加到容器中
public ServletRegistrationBean registrationBean(){
//構(gòu)造方法,第一個參數(shù)指定的是自己的Servlet含蓉,第二個參數(shù)指定的是映射的路徑频敛,是一個可變參數(shù),可以指定多個參數(shù)
ServletRegistrationBean bean=new ServletRegistrationBean(new MyServlet(),"/hello","/myFine");
bean.setLoadOnStartup(1);
return bean;
}
//注冊過濾器
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean bean=new FilterRegistrationBean();
bean.setFilter(new MyFilter()); //設(shè)置自己的Filter
bean.setUrlPatterns(Arrays.asList("/**")); //設(shè)置攔截的路徑
return bean;
}
//注冊監(jiān)聽器
@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean(){
ServletListenerRegistrationBean servletListenerRegistrationBean=new ServletListenerRegistrationBean<MyListener>(new MyListener());
return servletListenerRegistrationBean;
}
}
整合數(shù)據(jù)源
1馅扣、需要導(dǎo)入mysql的驅(qū)動程序
2斟赚、導(dǎo)入的依賴如下:
<!--導(dǎo)入原生的jdbc啟動器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--導(dǎo)入mysql的驅(qū)動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
3、我們可以在springBoot的配置文件中設(shè)置默認的mysql參數(shù)差油,如下:
## 配置Jdbc
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/jdbc
driver-class-name: com.mysql.jdbc.Driver
## type用來指定使用什么數(shù)據(jù)連接池
#type:
4汁展、springBoot中默認支持的連接池都在org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration
中展示出來,如下:
1)、`org.apache.tomcat.jdbc.pool.DataSource`
2)食绿、`com.zaxxer.hikari.HikariDataSource`
3)侈咕、`org.apache.commons.dbcp2.BasicDataSource`
5、當然我們也是可以自定義自己的數(shù)據(jù)源器紧,我們只需要在配置文件中使用spring-datasource.type
這個配置即可
整合Druid數(shù)據(jù)源
0耀销、https://www.cnblogs.com/niejunlei/p/5977895.html
1、導(dǎo)入依賴
<!-- 添加數(shù)據(jù)庫連接池 druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
2铲汪、在全局配置文件中設(shè)置使用指定的數(shù)據(jù)源
# 數(shù)據(jù)庫訪問配置
# 主數(shù)據(jù)源熊尉,默認的
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/jdbc
spring.datasource.username=root
spring.datasource.password=root
3、配置數(shù)據(jù)源參數(shù)掌腰,下面只是設(shè)置了部分的參數(shù)狰住,在全局配置文件中設(shè)置:
# 下面為連接池的補充設(shè)置,應(yīng)用到上面所有數(shù)據(jù)源中
# 初始化大小齿梁,最小催植,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置獲取連接等待超時的時間
spring.datasource.maxWait=60000
# 配置間隔多久才進行一次檢測,檢測需要關(guān)閉的空閑連接勺择,單位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一個連接在池中最小生存的時間创南,單位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打開PSCache,并且指定每個連接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 通過connectProperties屬性來打開mergeSql功能省核;慢SQL記錄
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
4稿辙、自定義一個DruidConfig,主要用來配置Druid气忠,如下:
@Configuration //指定Druid的數(shù)據(jù)源的配置類
public class DruidConfig {
//配置druid的參數(shù)邻储,并且將其注入到容器中
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DruidDataSource druid(){
return new DruidDataSource();
}
/**
* 配置監(jiān)控
* 1、配置一個管理后臺的Servlet
* 2旧噪、配置一個監(jiān)控的filter
*/
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean=new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
//設(shè)置初始化參數(shù)
Map<String,Object> initParams=new HashMap<>();
initParams.put("loginUsername","admin"); //設(shè)置登錄的用戶名
initParams.put("loginPassword","admin"); //設(shè)置登錄的密碼
initParams.put("resetEnable","false");
// initParams.put("allow","localhost"); //允許localhost訪問芥备,默認是所有都能訪問
// initParams.put("deny","IP地址"); //設(shè)置拒絕訪問的ip
bean.setInitParameters(initParams);
return bean;
}
//配置監(jiān)控的Filter
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean bean=new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,Object> initParams=new HashMap<>();
initParams.put("exclusions","*.css,*.js,/druid/*"); //設(shè)置不攔截器的路徑
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/**"));
return bean;
}
}
整合Mybatis
1、添加mybatis的啟動器舌菜,如下:
<!--導(dǎo)入mybatis的依賴-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
2萌壳、只需要引入這個啟動器,那么springBoot就會自動導(dǎo)入如下的mybatis
<mybatis.version>3.4.5</mybatis.version>
<mybatis-spring.version>1.3.1</mybatis-spring.version>
<spring-boot.version>1.5.6.RELEASE</spring-boot.version>
注解版
1日月、我們可以使用注解版本的mybatis袱瓮,只需要創(chuàng)建一個Mapper即可。如下:
@Mapper //表明這個是mapper接口爱咬,會自動掃描
public interface UserMapper {
@Select("select * from t_user where user_id=#{userId}")
User selectUser(Integer userId);
//插入尺借,自增主鍵返回
@Options(useGeneratedKeys = true,keyProperty = "userId")
@Insert("insert into t_user(name) values(#{name})")
int insertUser(User user);
}
2、使用注解版精拟,如果需要配置mybaits的一些參數(shù)燎斩,比如駝峰命名法等配置虱歪,那么我們可以自定義一個配置類,如下:
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Mybatis的配置類
*/
@Configuration
public class MybatisConfig {
//自定義一個定制器栅表,在其中可以針對mybatis配置不同的參數(shù)笋鄙,就相當于一個mybatis的主配置文件
@Bean //注入到容器中
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer() {
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true); //開啟駝峰命名法
//在其中還可以配置myabtis的其他配置
}
};
}
}
3、除了自己配置自定義的配置類來指定mybatis的參數(shù)配置怪瓶,我們還可以在全局配置文件中使用mybatis
.來進行相關(guān)的配置萧落,比如開啟駝峰命名,如下:
mybatis.configuration.map-underscore-to-camel-case=true
4洗贰、我們可以使用注解批量掃描mapper找岖,這樣我們就不需要在每一個Mapper接口都添加@Mapper
這個注解,我們只需要在主配置類中添加@MapperScan
這個注解即可敛滋,如下:
//批量掃描com.tellwess.springbootserver.mappers這個包下面的所有mapper
@MapperScan(value ="com.tellwess.springbootserver.mappers")
@SpringBootApplication
public class SpringbootServerApplication {
配置文件
1许布、我們將所有的mapper對應(yīng)的配置文件放在classpath:mapper/*.xml
下面的,其中的UserMapper.xml配置文件如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.tellwess.springbootserver.mappers.UserMapper" >
<select id="selectUser" resultType="com.tellwess.springbootserver.entities.User">
select * from t_user where user_id=#{userId}
</select>
<insert id="insertUser">
insert into t_user(name) values(#{name})
</insert>
</mapper>
2绎晃、創(chuàng)建一個UserMapper.java蜜唾,如下:
public interface UserMapper {
User selectUser(Integer userId);
int insertUser(User user);
}
3、在主配置類下創(chuàng)建添加批量掃描注解箕昭,將接口注入到容器中灵妨,如下:
//批量掃描com.tellwess.springbootserver.mappers這個包下面的所有mapper
@MapperScan(value ="com.tellwess.springbootserver.mappers")
@SpringBootApplication
public class SpringbootServerApplication {
4解阅、在全局配置文件中設(shè)置*.xml
配置文件的位置落竹,讓springBoot能夠掃描到,如下:
## 配置mybatis的全局配置文件
mybatis.mapper-locations=classpath:mapper/*.xml
# 開啟駝峰命名
mybatis.configuration.map-underscore-to-camel-case=true
# 在其中還可以配置mybatis其他的配置
springBoot對事務(wù)的支持
1货抄、在spring中我們?nèi)绻枰砑邮聞?wù)述召,可能需要配置切面或者聲明式注解,但是在springBoot中我們只需要直接使用即可蟹地,一切都為我們自動配置了积暖。
2、要想使用聲明式事務(wù)注解怪与,那么需要導(dǎo)入spring.tx
這個jar夺刑,其實這個jar在我們導(dǎo)入spring-boot-starter-jdbc
的時候就已經(jīng)為我們導(dǎo)入了,但是如果我們要是使用mybatis的話分别,那么只需要導(dǎo)入mybatis的場景啟動器即可遍愿,因為其中就已經(jīng)包含了jdbc的場景啟動器,因此我們只需要導(dǎo)入mybatis的場景啟動器即可耘斩,如下:
<!--導(dǎo)入mybatis的依賴-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
3沼填、在需要添加事務(wù)的類上添加一個注解即可@Transactional
,如下:
@Transactional
@Service
public class UserServiceImpl implements UserService {}
自動熱部署
- 每次修改代碼后都需要重新啟動程序括授,但是我們可以使用熱部署功能坞笙,只需要導(dǎo)入依賴即可岩饼。修改代碼完成后按住
Ctrl+F9
即可自動熱部署
<!--熱部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
SpringBoot對跨域的支持
- https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-cors
- 只需要在容器中注入
org.springframework.web.servlet.config.annotation.WebMvcConfigurer
這個實例即可,如下:
//添加跨域的功能
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
// .allowedOrigins("http://192.168.1.97")
// .allowedMethods("GET", "POST")
// .allowCredentials(false).maxAge(3600);
; //對所有的路徑都支持跨域的訪問
}
};
}
- 以上是針對全局配置的跨域薛夜,如果需要對某一個controller中的請求使用跨域籍茧,可以使用
@CrossOrigin(origins = "http://192.168.1.97:8080", maxAge = 3600)
這個注解標注在controller的類上,如下:
@CrossOrigin(origins = "http://192.168.1.97:8080", maxAge = 3600)
@RestController
public class IndexController{}
上傳文件大小的配置
- 配置文件的方式:
#multipart upload 文件上傳
#限制一次上傳的單個文件的大小
spring.http.multipart.maxFileSize=10Mb
#限制一次上傳的所有文件的總大小
spring.http.multipart.maxRequestSize=10Mb
解決同一個tomcat中不能運行多個springBoot項目問題
在配置文件中添加配置却邓,如下:
# 每個項目的值必須不同
spring.jmx.default-domain=demo
總結(jié)
1硕糊、整合mybaits和數(shù)據(jù)源配置的所有依賴如下:
<!--導(dǎo)入mysql的驅(qū)動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 添加數(shù)據(jù)庫連接池 druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<!--導(dǎo)入mybatis的依賴-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
springBoot配置文件能夠配置的全部配置
參考文檔
1、https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/
2腊徙、專欄