Spring Boot 知识笔记(配置文件)

Spring boot 提供了两种常用的配置文件,properties和yml文件。

1、yml

yml是YAML(YAML Ain't Markup Language)语言的文件,以数据为中心,比json、xml等更适合做配置文件.

使用空格 Space 缩进表示分层,不同层次之间的缩进可以使用不同的空格数目

注意:key后面的冒号,后面一定要跟一个空格,树状结构

         server: 

                  port: 8090 

                 session-timeout: 30 

                 tomcat.max-threads: 0 

                  tomcat.uri-encoding: UTF-8

2、properties

properties形式比较简单,key=value

server.port=8090
server.session-timeout=30
server.tomcat.max-threads=0
server.tomcat.uri-encoding=UTF-8

配置文件官方参考:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#common-application-properties

3、通过配置文件自动映射属性

1)application.properties文件中增加一个属性
#文件上传路径配置
web.file.path=D:/work/masterSpring/code/xdclass_springboot/src/main/resources/static/images/
2)controller上面增加配置

4、通过配置文件自动映射实体

1)配置文件application.properties文件中增加实体属性
#测试配置文件注入
test.domain=www.class.net
test.name=springboot

2)新建一个实体类ServerSetting,包括domain和name两个属性。


package net.xdclass.demo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Component
@ConfigurationProperties  //设置相关属性
@PropertySource(value="application.properties")   //指定配置文件

public class ServerSetting {
    @Value("${test.name}")  //注入值
    private String name;
    @Value("${test.domain}")
    private String domain;

    public String getName() {
        return name;
    }

    public String getDomain() {
        return domain;
    }

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

    public void setDomain(String domain) {
        this.domain = domain;
    }
}

 3)在controller中注入这个类,返回类的实体









原文地址:https://www.cnblogs.com/Eleven-Liu/p/10920259.html