3.Springboot 之 檔案結構和配置檔案
專案檔案結構
新建的Springboot專案的檔案結構如下:
|-customer(專案名稱)
| - src
| | - main
| | | - java
| | | - resources
| | | | - static
| | | | - public
| | - test
| | | - java
| - pom.xml
| - customer.iml
customer
:是專案名稱;
src/main/java
:目錄下放置所有java檔案(原始碼檔案);
src/main/resources
:放置所有的配置檔案、頁面檔案、靜態資原始檔;
src/main/resources/static
:是靜態資原始檔目錄,在這個目錄中的所有檔案將可以被直接訪問,如果沒有這個資料夾可自行建立;
src/main/resources/public
:作用和src/main/resources/static
目錄一樣。
配置檔案
Springboot把使用Spring來開發Web專案的很多配置進行了統一管理,且都配置了預設值。很多預設值是基本不用修改的,但也有部份配置是不能滿足實際需求的,所以需要修改這些配置。
Springboot預設支援兩種配置檔案型別:.properties
和.yml
比如將預設的8080埠修改為9090,則可以配置為:
application.properties :
server.port = 9090
application.yml :
server:
port: 9090
注意:Springboot會自動在src/main/resources/
目錄下找application.properties
或application.yml
配置檔案,找到後將應用此配置檔案中的配置,否則使用其預設值。這兩種型別的配置檔案有其一即可,也可兩者並存。
.properties
配置檔案的優先順序更高,將在application.properties
中配置了server.port=9090
同時也在application.yml
中配置了server:
port: 9091
時,系統將使用.properties
9090
埠。
常用配置
server.port=9090 # 服務埠號
server.tomcat.uri-encoding=UTF-8 #以Tomcat為web容器時的字元編碼
spring.application.name=customer # 應用名稱,一般就是專案名稱,這個名稱在SpringCloud中比較關鍵
spring.profiles.active=dev #指定當前的活動配置檔案,主要用於多環境多配置檔案的應用中
spring.http.encoding.charset=UTF-8 #http請求的字元編碼
spring.http.multipart.max-file-size=10MB #設定檔案上傳時單個檔案的大小限制
spring.http.multipart.max-request-size=100MB #設定檔案上傳時總檔案大小限制
spring.thymeleaf.prefix=classpath:/templates/ #配置在使用Thymeleaf做頁面模板時的字首,即頁面所在路徑
spring.thymeleaf.suffix=.html #設定在使用Thymeleaf做頁面模板時的字尾
spring.thymeleaf.cache=false #設定在使用Thymeleaf做頁面模板時是否啟用快取
spring.mvc.static-path-pattern=/** #設定靜態資源的請求路徑
spring.resources.static-locations=classpath:/static/,classpath:/public/ #指定靜態資源的路徑
##以下是使用MySQL資料庫的配置
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect #指定資料庫方言
hibernate.show_sql=true #是否顯示sql語句
hibernate.hbm2dll.auto=update #設定使用Hibernate的自動建表方式
entitymanager.packagesToScan=com.zslin #設定自動掃描的包字首
spring.datasource.url=jdbc:mysql://localhost:3306/customer?\
useUnicode=true&characterEncoding=utf-8&useSSL=true&autoReconnect=true #資料庫連結
spring.datasource.username=root #資料庫使用者名稱
spring.datasource.password=123 #資料庫使用者對應的密碼
spring.datasource.driver-class-name=com.mysql.jdbc.Driver #資料庫驅動名稱
hibernate.hbm2dll.auto
有幾種配置:
-
create
:每次載入Hibernate時都會刪除上一次生成的表,然後重新生成新表,即使兩次沒有任何修改也會這樣執行,這就導致每次啟動都是一個新的資料庫,也是導致資料丟失的重要原因。 -
create-drop
:每次載入Hibernate時都會生成表,但當SessionFactory關閉時,所生成的表將自動刪除。 -
update
:最常用的屬性值,第一次載入Hibernate時建立資料表(前提是需要先有資料庫),以後載入HIbernate時只會根據model更新,即使model已經刪除了某些屬性,資料表也不會隨之刪除欄位。 -
validate
:每次載入Hibernate時都會驗證資料表結構,只會和已經存在的資料表進行比較,根據model修改表結構,但不會建立新表。
以上是我在使用中比較常用的配置資訊!