1. 程式人生 > >Spring Boot 配置檔案設定(三)

Spring Boot 配置檔案設定(三)

簡介

上篇我們做了一些簡單的執行檔案的配置,本篇帶領大家來認識常用的一些配置,當然了關於Spring Boot 這些配置太多太多了,如果想了解更多的話直接上官網參考一下,瞭解相關案例如本篇的配置。 application.properties配置官方指南參考

Spring Boot有以下方式配置

application.properties配置

IntelliJ IDEA 開發工具中建立專案的時候,預設的配置檔案是application.properties,接下來我們就學習一下然後配置一些我們在開發中經常用到的配置項,進入帶領我們揭開Spring Boot 專案的神祕的面紗。
在下面的文件中我會在每個配置中進行註解,這樣能更好的瞭解,當然官方文件有我們所需的全部配置,大家如果專案開發中有需求那麼可以進入

application.properties配置官方指南參考

英: Appendix A. Common application properties

Various properties can be specified inside your application.properties file, inside your application.yml file, or as command line switches.
This appendix provides a list of common Spring Boot properties and references to the underlying classes that consume them.
[Note]
Property contributions can come from additional jar files on your classpath, so you should not consider this an exhaustive list.
Also, you can define your own properties.
[Warning]
This sample file is meant as a guide only. Do not copy and paste the entire content into your application. Rather, pick only the properties that you need.

譯: 官方指南者三段話概況了今天我們要講得內容:

可以在application.properties檔案中,application.yml檔案中或命令列開關中指定各種屬性。 本附錄提供了常用Spring Boot屬性的列表以及對使用它們的基礎類的引用。
[注意]
屬性貢獻可以來自類路徑上的其他jar檔案,因此您不應將此視為詳盡的列表。 此外,您可以定義自己的屬性。
[警告]
此示例檔案僅供參考。 不要將整個內容複製並貼上到您的應用程式中。 相反,只選擇您需要的屬性。

所以我們在新增某些配置屬性的時候,一定要根據自己的需要來新增,不然有時出錯了,不知道哪裡找問題。

常用的application.properties配置

一般情況下在src目錄下的/main/resource資料夾中新建*application.properties*檔案,目錄結構如下:

|--src
   |--main
      |--resources
         |--application.properties

我們接下來編寫一些常用的屬性配置,大家在開發中需要到哪些就直接去檢視一下:

#啟用除錯日誌。
debug=false
#啟用跟蹤日誌。
trace=false

#--------------------------------------
# LOGGING 日記
#--------------------------------------
# 日誌配置檔案的位置。 例如,Logback的classpath:logback.xml
logging.config=classpath:logback.xml
# 日誌檔名(例如,`myapp.log`)。名稱可以是精確位置或相對於當前目錄。
logging.file=property.log
# 最大日誌檔案大小。 僅支援預設的logback設定
logging.file.max-size=10MB
# 日誌檔案的位置。 例如,`/ var / log`。
logging.path=/var/log

#---------------------------------
# AOP
#---------------------------------
# 使用AOP 切面程式設計
spring.aop.auto=true
#是否要建立基於子類的(CGLIB)代理(true),而不是基於標準Java介面的代理(false)
spring.aop.proxy-target-class=true

#--------------------------------
# Email
#--------------------------------
# 編碼格式
spring.mail.default-encoding=UTF-8
# SMTP伺服器主機
spring.mail.host=smtp.property.com
#SMTP伺服器埠
spring.mail.port=7800
# 登入SMTP使用者名稱
spring.mail.username=property
# 登入SMTP密碼
spring.mail.password=123456

#--------------------------------
# WEB 屬性配置
#--------------------------------
# 伺服器應繫結的網路地址
server.address=127.0.0.1
# 是否啟用了響應壓縮
server.compression.enabled=false
# 聯結器在關閉連線之前等待另一個HTTP請求的時間。 未設定時,將使用聯結器的特定於容器的預設值。 使用值-1表示沒有(即無限)超時
server.connection-timeout=2000
# 錯誤控制器的路徑
server.error.path=/error
# 是否啟用HTTP / 2支援,如果當前環境支援它。
server.http2.enabled=false
# 伺服器埠預設為:8080
server.port=8084
# SP servlet的類名。
server.servlet.jsp.class-name=org.apache.jasper.servlet.JspServlet
# 主排程程式servlet的路徑。
server.servlet.path=/home
# 會話cookie名稱
server.servlet.session.cookie.name=propertydemo

#------------------------------
# HTTP encoding
#------------------------------
# HTTP請求和響應的字符集。 如果未明確設定,則新增到“Content-Type”標頭。
spring.http.encoding.charset=UTF-8
# 是否啟用http編碼支援。
spring.http.encoding.enabled=true
#--------------------
# MULTIPART (MultipartProperties)
#--------------------
# 是否啟用分段上傳支援
spring.servlet.multipart.enabled=true
# 上傳檔案的中間位置
spring.servlet.multipart.location=/log
# 最大檔案的大小
spring.servlet.multipart.max-file-size=1MB
# 最大請求大小
spring.servlet.multipart.max-request-size=10MB
# 是否在檔案或引數訪問時懶惰地解析多部分請求。
spring.servlet.multipart.resolve-lazily=false
#--------------------------------------------
# SPRING SESSION JDBC (JdbcSessionProperties)
#--------------------------------------------
# cron表示式用於過期的會話清理作業
spring.session.jdbc.cleanup-cron=0 * * * * *
# 資料庫模式初始化模式
spring.session.jdbc.initialize-schema=embedded
# 用於初始化資料庫模式的SQL檔案的路徑
spring.session.jdbc.schema=classpath:org/springframework/session/jdbc/[email protected]@[email protected]@.sql
# 用於儲存會話的資料庫表的名稱
spring.session.jdbc.table-name=SPRING_SESSION

#----------------------------------
# MONGODB 資料庫配置
#----------------------------------
# 資料庫名稱
spring.data.mongodb.database=demo
# host 配置
spring.data.mongodb.host=127.0.0.1
# 登入使用者名稱
spring.data.mongodb.username=property
# 登入密碼
spring.data.mongodb.password=123456
# 埠號,自己根據安裝的mongodb埠配置
spring.data.mongodb.port=9008
# 要啟用的Mongo儲存庫的型別
spring.data.mongodb.repositories.type=auto
# 連線資料uri
spring.data.mongodb.uri=mongodb://localhost/test

#---------------------------------------
# DATASOURCE 資料庫配置
#---------------------------------------
# MySql jdbc Driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 連線資料庫
# demo表示的是你建立的資料庫;
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo?useSSL=false&requireSSL=false&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
# 資料庫使用者名稱
spring.datasource.username=root
# 資料庫密碼
spring.datasource.password=123456
#-----------------------------------
# Jpa使用
#-----------------------------------
# 目標資料庫進行操作,預設情況下自動檢測。可以使用“databasePlatform”屬性設定。
#spring.jpa.database= demo1
# 要操作的目標資料庫的名稱,預設情況下自動檢測。 也可以使用“Database”列舉來設定。
#spring.jpa.database-platform=DEMO
# DDL模式 一般有這幾種方式,Spring Boot會根據是否認為您的資料庫是嵌入式的,為您選擇一個預設值

# create:每次啟動該程式,沒有表的會新建表,表內有資料都會清空,結束時,並未清空表
# create-drop:每次啟動、結束程式的時都會清空表,而且啟動時會重新建立表
# update:每次啟動程式時,沒有表的會建立表,表不會清空,檢查表字段是否相同,不同則更新
# validate:每次啟動程式時,校驗資料與表(欄位、型別等)是否相同,不同會報錯
# none:在所有其他情況下,預設為none
spring.jpa.hibernate.ddl-auto=update
# 是否啟用SQL語句的日誌記錄
spring.jpa.show-sql=true

#----------------------------------------
# TESTING PROPERTIES
#----------------------------------------
# 要替換的現有DataSource的型別
spring.test.database.replace=any
# MVC列印選項
spring.test.mockmvc.print=default

# ---------------大家檢視文件進行配置,不一一列舉了----------------------

#  各個屬性註解在檢視常用配置檔案application.properties中

# FREEMARKER

# DEVTOOLS配置

# SPRING HATEOAS

# HTTP message conversion

# GSON

# JDBC

# JEST (Elasticsearch HTTP client) (JestProperties)

# CASSANDRA (CassandraProperties)
# --------------------------等等----------------------------------

檢視常用配置檔案application.properties

自定義屬性

由於有時為了方便專案的開發維護,我們可能需要到自定義配置屬性,接下來我們也來搞一下自定義屬性配置。

application.properties自定義配置屬性:

1.application.properties新增:

#--------------------------------
# 自定義屬性
#--------------------------------
com.eirunye.defproname="root"
com.eirunye.defpropass="123456"

2.在DefPropertyController.class引用

@RestController
public class DefPropertyController {

    @Value("${com.eirunye.defproname}")
    private String defProName;

    @Value("${com.eirunye.defpropass}")
    private String defProPass;

    @RequestMapping(value = "/defproprety")
    public String defPropretyUser() {
        return "這個自定義屬性名為: " + defProName + ", 密碼為:" + defProPass;
    }
}
  • 注意
    在獲取自定義屬性時一定要嚴格按照配置檔案來獲取並且Value裡面的字串一定是$+花括號{***},花括號裡面的***表示為:application.properties裡面自定義的字串,所以本例就是表示為:@Value("${com.eirunye.defproname}")
    如果application.properties有自定義為test.ok="haha",同樣的獲取方式為:@Value("${test.ok}")

3.測試這裡暫未使用測試程式碼的方式,後面的文章會講到

  • IntelliJ IDEA訪問
http://localhost:8084/defproprety

通過Bean的形式獲取

假如我們遇到這樣情況,自定義屬性多,然後每個都是通過@Value(${""})方式的話可能會很容易出錯,那麼我們可以採用以下方式。

1.新建一個Properties.class
新增@ConfigurationProperties(prefix = "com.eirunye")//表示的是通過自定義屬性查詢,如果自定義是:test.ok=haha,則該這樣表示:@ConfigurationProperties(prefix = "test")

@ConfigurationProperties(prefix = "com.eirunye")//新增該註解
public class Properties {
    private String defproname;
    private String defpropass;
//  get/set方法
    public String getDefproname() {
        return defproname;
    }
    public void setDefproname(String defproname) {
        this.defproname = defproname;
    }
    public String getDefpropass() {
        return defpropass;
    }
    public void setDefpropass(String defpropass) {
        this.defpropass = defpropass;
    }}

2.在controller包下建立 DefBeanPropertyController.class

@RestController
public class DefBeanPropertyController {
   //通過 Autowired註解來獲取到 Properties屬性,注:Autowired是按型別進行裝配,可獲取它所裝配類的屬性
    @Autowired
    Properties properties;

    @RequestMapping(value = "/bean/defproperty")
    public String getDefBeanProperties() {
        return "這是通過Bean註解的方式獲取屬性: " + properties.getDefproname() + ",密碼為: " + properties.getDefpropass();
    }}

3.在專案的入口檔案Application添加註解**@EnableConfigurationProperties**
最後加上包名不然可能找不到掃描檔案如:@EnableConfigurationProperties({com.eirunye.defpropertys.bean.Properties.class})

@SpringBootApplication
@EnableConfigurationProperties({com.eirunye.defpropertys.bean.Properties.class})//添加註解bean的掃描檔案
public class DefpropertysApplication {

	public static void main(String[] args) {
		SpringApplication.run(DefpropertysApplication.class, args);
	}
}

4.測試
IntelliJ IDEA訪問

建立檔案xxx.properties檔案方式

我們可以自己建立一個自定義屬性的檔案如本例def.properties,(注:一般都是以 .properties 檔案結尾)

1.新增自定義def.properties配置如下:

#--------------------------------
# 自定義屬性
#--------------------------------
# 使用者名稱
com.eirunye.defineuser="property"
# 年齡
com.eirunye.defineage=20

2.建立 DefineProperties.class

@Configuration
@ConfigurationProperties(prefix = "com.eirunye")//添加註解 ConfigurationProperties "com.eirunye"表示的是自定義屬性
@PropertySource("classpath:defines.properties")// 添加註解 PropertySource 該註解能根據路徑掃描到我們的檔案
public class DefineProperties {
//    這裡可以通過@Value("${}")方式新增,我已經遮蔽掉了,直接通過ConfigurationProperties註解的方式
//    @Value("${com.eirunye.defineuser}")
    private String defineuser;
//    @Value("${com.eirunye.defineage}")
    private int defineage;
// get/set方法
    public String getDefineuser() {
        return defineuser;
    }
    public void setDefineuser(String defineuser) {
        this.defineuser = defineuser;
    }
    public int getDefineage() {
        return defineage;
    }
    public void setDefineage(int defineage) {
        this.defineage = defineage;
    }}

3.在DefinePropertiesController.class引用

@RestController
public class DefinePropertiesController {
    @Autowired
    DefineProperties defineProperties;
    @RequestMapping(value = "define/Properties")
    public String getDefinePropertiesData(){
        return "新建檔案自定義屬性姓名:"+defineProperties.getDefineuser()+",新建檔案自定義屬性年齡:"+defineProperties.getDefineage();
    }
}

4.別忘了在Application裡面新增配置@EnableConfigurationProperties,即:@EnableConfigurationProperties({com.eirunye.defpropertys.bean.Properties.class,com.eirunye.defpropertys.bean.DefineProperties.class})

5.測試

http://localhost:8084/define/Properties

下載application.properties案例demo

application.yml配置

由於application.properties配置有點繁瑣,簡潔是我們非常喜歡的,那麼在Spring Boot程式裡面當然也是可以用.yml檔案來配置的,接下來讓我們進入對.yml檔案的一些相關配置吧,官方文件Using YAML Instead of Properties

常見的配置

首先在src目錄下的/main/resource資料夾中新建application.yml、application-dev.yml、application-prod.yml三個檔案,刪除application.properties檔案,目錄結構如下:

|--src
   |--main
      |--resources
         |--application.yml
         |--application-dev.yml
         |--application-prod.yml

相信很多人要罵街了,這什麼情況不是說,yml配置很給力嗎?怎麼還有建立那麼多檔案,這不是比上面的 application.properties配置還多此一舉嗎?莫急接下來讓我們來看看.yml的配置之後,我相信你肯定在專案中會喜歡用它。

常見的配置屬性如下: 【注意: 這裡屬性之間的間隔必須按照要求而來,如:冒號後面要空格】
application.yml 配置

spring:
  profiles:
    active: dev   #引用 application-dev.yml檔案,這裡我們可以改為 prod,表示引用application-prod.yml檔案
  datasource:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/demo?useSSL=false&requireSSL=false&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
      username: root
      password: 12346
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  data:
    mongodb:
      host: 127.0.0.1
      uri: mongodb://localhost/test
      username: root
      password: 123456
      database: test
  test:
    database:
      replace: any
    mockmvc:
      print: default
  servlet:
    multipart:
      enabled: true

application-dev.yml 可以當成正式伺服器埠

server:
  port: 8084

application-prod.yml 可以當成測試伺服器埠

server:
  port: 8080

自定義yml配置

在application.yml配置

1.和上面的application.properties類似,但是需要注意的是格式問題

com:
  eirunye:
    ymlname: ymlroot
    ymlpass: yml123456

2.通過@Value("${com.eirunye.ymlname}")獲取

@RestController
public class YmlPropertiesController{
    @Value("${com.eirunye.ymlname}")
    private String ymlname;

    @Value("${com.eirunye.ymlpass}")
    private String ymlpass;

    @RequestMapping(value = "yml/proprety")
    public String getYmlPropreties() {
        return "這個自定義屬性名為: " + ymlname+ ", 密碼為:" + ymlpass;
    }
}

3.測試—訪問:

http://localhost:8084/yml/proprety

通過Bean方式獲取和application.properties方式一樣

1.建立YmlPropertyBean.class

@ConfigurationProperties(prefix = "com.eirunye")//新增該註解
public class YmlPropertyBean {

    private String ymlname;
    private String ymlpass;
// get/set方法.....
}

2.在 YmlPropertyBeanController.class引用

@RestController
public class YmlPropertyBeanController {
    @Autowired
    YmlPropertyBean propertyBean;
    @RequestMapping(value = "/bean/ymlproperty")
    public String getYmlPropertyData(){
        return "這個bean自定義屬性名為: " + propertyBean.getYmlname()+ ", 密碼為:" + propertyBean.getYmlpass();
    }
}

3.測試-訪問

http://localhost:8084/bean/ymlproperty

下載.yml案例demo

總結

1.本篇主要講得配置檔案,到此就結束了,在開發中這是我們經常用到。
2.在本篇有些相關配置,本例的程式碼例項還沒涉及到,接下來會繼續結合相關的配置案例繼續更新。
3.相信大家也有所掌握。

推薦

如果大家想了解更多的Spring Boot相關博文請進入