SpringBoot实战:SpringBoot之本地配置(三)

springboot会自动加载application.yml和application.properties文件做为默认配置文件,springboot会同时加载这两个文件,可是会个优先级,顺序高优先级的内容会覆盖底优先级的内容,造成互补配置,若是在不一样的目录中存在多个配置文件,它的读取顺序是:
一、config/application.properties(项目根目录中config目录下)
二、config/application.yml
三、application.properties(项目根目录下)
四、application.yml
五、resources/config/application.properties(项目resources目录中config目录下)
六、resources/config/application.yml
七、resources/application.properties(项目的resources目录下)
八、resources/application.ymljava

下面咱们就来演示下,演示步骤以下:web

在resource/config文件下新增application.yml
spring:
  application:
    id: spring-boot-yml-demo  #应用id
    name : spring-boot-yml-demo #应用名称

而application.properties文件添加一样的配置spring

#应用id
spring.application.id=spring-boot-wusy-demo
#应用名称
spring.application.name=spring-boot-wusy-demo
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wusy
 * Company: xxxxxx科技有限公司
 * Createtime : 2020/2/24 21:54
 * Description :
 */
@RestController
@RequestMapping("/api/demo")
public class HelloWorldController {

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


    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "hello world," + name;
    }
}

运行应用,打开浏览器,在地址栏输入http://127.0.0.1:8787/api/demo/hello,观察结果api

删除application.yml中的配置后再重启应用,在地址栏输入http://127.0.0.1:8787/api/demo/hello,观察结果浏览器

从演示结果能够看出,确实是顺序高优先级的内容会覆盖底优先级的内容。springboot

同时优先级低的配置能够读取优先级高的配置,接下来演示在application.properties新增一个配置读取application.yml中的spring.application.name的配置值。app

在applicataion.yml配置新增配置,并修改以前读取配置的类,spring-boot

wusy.application.name = ${spring.application.name}
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wusy
 * Company: xxxxxx科技有限公司
 * Createtime : 2020/2/24 21:54
 * Description :
 */
@RestController
@RequestMapping("/api/demo")
public class HelloWorldController {

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


    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "hello world," + name;
    }
}

运行应用,打开浏览器,在地址栏输入http://127.0.0.1:8787/api/demo/hello,观察结果spa

经过以上的演示,知道配置文件如何经过优先级造成造成互补配置。code

相关文章
相关标签/搜索