天天看點

SpringBoot學習筆記(三)—— SpringBoot配置檔案

SpringBoot配置檔案類型

  • SpringBoot配置檔案類型和作用

SpringBoot是基于約定的,是以很多配置都有預設值,但如果想使用自己的配置替換預設配置的話,就可以使用application.properties或者application.yml(application.yaml)進行配置。

SpringBoot預設會從Resources目錄下加載application.properties或application.yml(application.yaml)檔案,其中application.properties檔案是鍵值對類型的檔案。

  • application.yml配置檔案

YML檔案格式是YAML (YAML Aint Markup Language)編寫的檔案格式,YAML是一種直覺的能夠被電腦識别的的資料資料序列化格式,并且容易被人類閱讀,容易和腳本語言互動的,可以被支援YAML庫的不同的程式設計語言程式導入,比如: C/C++, Ruby, Python, Java, Perl, C#, PHP等。YML檔案是以資料為核心的,比傳統的xml方式更加簡潔。

YML檔案的擴充名可以使用.yml或者.yaml。

  • yml配置檔案的文法

1.配置普通資料

文法: 

  ​    key: 

  ​        key1: value1

  ​        key2: value2

  或者:  key: {key1: value1,key2: value2}

示例代碼:

  person:
    name: haohao
    age: 31
    addr: beijing

  #或者

  person: {name: haohao,age: 31,addr: beijing}
           

注意:key1前面的空格個數不限定,在yml文法中,相同縮進代表同一個級别

2.配置Map資料

同上面的對象寫法

3.配置數組(List、Set)資料

文法: 

  ​    key: 

  ​        - value1

  ​        - value2

  或者:

  ​    key: [value1,value2]

  city:
    - beijing
    - tianjin
    - shanghai
    - chongqing
    
  #或者

  city: [beijing,tianjin,shanghai,chongqing]

  #集合中的元素是對象形式
  student:
    - name: zhangsan
      age: 18
      score: 100
    - name: lisi
      age: 28
      score: 88
    - name: wangwu
      age: 38
      score: 90
           

注意:value1與之間的 - 之間存在一個空格

  • SpringBoot配置資訊的查詢

SpringBoot的配置檔案,主要的目的就是對配置資訊進行修改的,但在配置時的key,我們可以查閱SpringBoot的官方文檔

文檔URL:https://docs.spring.io/spring-boot/docs/2.0.1.RELEASE/reference/htmlsingle/#common-application-properties

常用的配置:

# QUARTZ SCHEDULER (QuartzProperties)
spring.quartz.jdbc.initialize-schema=embedded # Database schema initialization mode.
spring.quartz.jdbc.schema=classpath:org/quartz/impl/jdbcjobstore/[email protected]@[email protected]@.sql # Path to the SQL file to use to initialize the database schema.
spring.quartz.job-store-type=memory # Quartz job store type.
spring.quartz.properties.*= # Additional Quartz Scheduler properties.

# ----------------------------------------
# WEB PROPERTIES
# ----------------------------------------

# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.port=8080 # Server HTTP port.
server.servlet.context-path= # Context path of the application.
server.servlet.path=/ # Path of the main dispatcher servlet.

# HTTP encoding (HttpEncodingProperties)
spring.http.encoding.charset=UTF-8 # Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly.

# JACKSON (JacksonProperties)
spring.jackson.date-format= # Date format string or a fully-qualified date format class name. For instance, `yyyy-MM-dd HH:mm:ss`.

# SPRING MVC (WebMvcProperties)
spring.mvc.servlet.load-on-startup=-1 # Load on startup priority of the dispatcher servlet.
spring.mvc.static-path-pattern=/** # Path pattern used for static resources.
spring.mvc.view.prefix= # Spring MVC view prefix.
spring.mvc.view.suffix= # Spring MVC view suffix.

# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
spring.datasource.password= # Login password of the database.
spring.datasource.url= # JDBC URL of the database.
spring.datasource.username= # Login username of the database.

# JEST (Elasticsearch HTTP client) (JestProperties)
spring.elasticsearch.jest.password= # Login password.
spring.elasticsearch.jest.proxy.host= # Proxy host the HTTP client should use.
spring.elasticsearch.jest.proxy.port= # Proxy port the HTTP client should use.
spring.elasticsearch.jest.read-timeout=3s # Read timeout.
spring.elasticsearch.jest.username= # Login username.
           

我們可以通過配置application.poperties 或者 application.yml 來修改SpringBoot的預設配置,例如:

application.properties檔案

server.port=8888
server.servlet.context-path=demo
           

application.yml檔案

server:
  port: 8888
  servlet:
    context-path: /demo
           

配置檔案與配置類的屬性映射方式

  • 使用注解@Value映射

我們可以通過@Value注解将配置檔案中的值映射到一個Spring管理的Bean的字段上,例如:

application.properties配置如下:

person:
  name: zhangsan
  age: 18
           

或者,application.yml配置如下:

person:
  name: zhangsan
  age: 18
           

實體Bean代碼如下:

@Controller
public class QuickStartController {

    @Value("${person.name}")
    private String name;
    @Value("${person.age}")
    private Integer age;


    @RequestMapping("/quick")
    @ResponseBody
    public String quick(){
        return "springboot 通路成功! name="+name+",age="+age;
    }

}
           

浏覽器通路位址:http://localhost:8080/quick 結果如下:

SpringBoot學習筆記(三)—— SpringBoot配置檔案
  • 使用注解@ConfigurationProperties映射

通過注解@ConfigurationProperties(prefix="配置檔案中的key的字首")可以将配置檔案中的配置自動與實體進行映射

application.properties和application.yml配置如上。

實體Bean代碼如下:

@Controller
@ConfigurationProperties(prefix = "person")
public class QuickStartController {

    private String name;
    private Integer age;

    @RequestMapping("/quick")
    @ResponseBody
    public String quick(){
        return "springboot demo2通路成功! name="+name+",age="+age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
           

浏覽器通路位址:http://localhost:8080/quick 結果如下:

SpringBoot學習筆記(三)—— SpringBoot配置檔案

注意:使用@ConfigurationProperties方式可以進行配置檔案與實體字段的自動映射,但需要字段必須提供set方法才可以,而使用@Value注解修飾的字段不需要提供set方法。

繼續閱讀