Spring Boot【全解】4

四、SpringBoot的配置文件

1.1        SpringBoot配置文件类型

1.1.1   SpringBoot配置文件类型和作用

查看起步依赖:spring-boot-starter-parent

<resource>
    <filtering>true</filtering>
    <directory>${basedir}/src/main/resources</directory>
    <includes>
        <include>**/application*.yml</include>
        <include>**/application*.yaml</include>
        <include>**/application*.properties</include>
    </includes>
</resource>

这里注意:后加载的配置文件会覆盖之前的配置文件。

SpringBoot是基于约定的,所以很多配置都有默认值,但如果想使用自己的配置替换默认配置的话,就可以在src/main/resources使用application.properties或者application.yml(application.yaml)进行配置。

SpringBoot默认会从Resources目录下加载application.properties或application.yml(application.yaml)文件

其中,application.properties文件是键值对类型的文件,之前一直在使用,所以此处不在对properties文件的格式进行阐述。除了properties文件外,SpringBoot还可以使用yml文件进行配置,下面对yml文件进行讲解。

可以在src/resource下创建application.properties文件

# 服务器的端口号
server.port=8888
# 当前web应用名称
server.servlet.context-path=/demo

1.1.2   application.yml配置文件(了解)

1.1.2.1  yml配置文件简介

YML文件格式是YAML (YAML Aint Markup Language)编写的文件格式,YAML是一种直观的能够被电脑识别的的数据序列化格式,并且容易被人类阅读,容易和脚本语言交互的,可以被支持YAML库的不同的编程语言程序导入,比如: C/C++, Ruby, Python, Java, Perl, C#, PHP等。YML文件是以数据为核心的,比传统的xml方式更加简洁。

YML文件的扩展名可以使用.yml或者.yaml。

1.1.2.2  yml配置文件的语法

1.1.2.2.1        配置普通数据

语法: key: value

示例代码:

# 属性的配置
name: itcast

注意:value之前有一个空格

1.1.2.2.2        配置对象数据

语法:

​ key:

​ key1: value1

​ key2: value2

​ 或者:

​ key: {key1: value1,key2: value2}

示例代码:

# 对象的配置
person:
  name:
itcast
  age: 18
  addr: beijing

# 行内对象配置
person1: {name: itcast,age: 18,addr: beijing}

# 配置端口
#改变application.properties
server:
  port:
8890
  servlet:
    path:
/demo1
 
 

 

注意:key1前面的空格个数不限定(一般使用tab键),在yml语法中,相同缩进代表同一个级别

  •  
1.1.2.2.3        配置Map数据

同上面对象的形式

语法:

​ map:

key: value1

key: value2

示例代码:

# map结构
map:
  key1:
value1
  key2: value2

 

 

1.1.2.2.4        配置数组(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

# 或者使用行内注入
student: [{name: zhangsan,age: 18,score: 100},{name: lisi,age: 28,score: 88},{name: wangwu,age: 38,score: 90}]

 

注意:value1与之间的 - 之间存在一个空格

1.1.3   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/tables_@@platform@@.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

1.2        配置文件与配置类的属性映射方式

1.2.1   使用注解@Value映射

我们可以通过@Value注解将配置文件中的值映射到一个Spring管理的Bean的字段上

例如:

application.properties配置如下:

person.name=zhangsan
person.age=18

或者,application.yml配置如下:

person:
  name: zhangsan
  age: 18

实体Bean代码如下:

@Controller
public class QuickStartController2 {

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

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

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

}
 

浏览器访问地址:http://localhost:8888/demo/quick2 结果如下:

 

 

1.1.1   使用注解@ConfigurationProperties映射

通过注解@ConfigurationProperties(prefix="配置文件中的key的前缀")可以将配置文件中的配置自动与实体进行映射

application.properties配置如下:

person.name = zhangsan
person.age = 18

或者,application.yml配置如下:

person:
  name: zhangsan
  age: 18

实体Bean代码如下:

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

    private String name;

    private Integer age;

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

    @RequestMapping("/quick3")
    @ResponseBody
    public String quick(){
        return "springboot3 访问成功! name="+name+",age="+age;
    }

}
 

浏览器访问地址:http://localhost:8888/demo/quick3 结果如下:

 

 

注意:

1:使用@ConfigurationProperties方式可以进行配置文件与实体字段的自动映射,但需要字段必须提供set方法才可以,而使用@Value注解修饰的字段不需要提供set方法。

2:使用@ConfigurationProperties方式使用的属性名称必须与配置文件的属性名称一致。

 

1.1.1        使用注解@ConfigurationProperties映射

添加执行器

点击:【Open Documentation】

 

 

 

 

将坐标代码放置到pom.xml中:

<!--配置@ConfigurationProperties注解的执行器-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

当添加执行器的坐标之后,我们点击“Maven Projects”,并刷新maven工程,可以发现警告消失

 

 

这样做的好处在于,在QuickStartController3.java中提供属性的get方法时,我们可以在application.yml中找到使用的关联对象,方便我们对yml文件的配置。

(1):QuickStartController3.java

@ConfigurationProperties(prefix = "person")
public class QuickStartController3 {

    private String name;

    private Integer age;

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

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

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }
 

(2):application.yml文件

读取QuickStartController3.java的配置。

 

 

posted @ 2022-03-08 17:13  小年的西瓜  阅读(57)  评论(0编辑  收藏  举报