描述:
1、SpringBoot项目中的配置,properties和yml的优先关系,当application.properties和application.yml文件同时存在的时候,会优先的加载properties文件。
2、在controller中获取yml配置文件中的信息
3、多个yml文件存在时,根据配置加载指定的配置文件
项目结构
读取配置文件
application.yml
spring:
application:
name: maven2
server:
port: 8081
student:
name: 张三
age: 18
界面中的调用,读取:
package com.test.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@Value("${student.name}")
private String name;
@RequestMapping("/")
public String test1(){
System.out.println(name);
return "index";
}
}
加载指定的yml文件
步骤:首先在properties中配置指定的文件,然后配置为指定的yml文件即可,具体如下图所示:
根据yml文件中的中间的标识进行读取。
项目启动的文件:
package com.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Maven2Application {
public static void main(String[] args) {
SpringApplication.run(Maven2Application.class, args);
}
}
然后,可以启动进行查看效果。启动之后,可看到如下的效果:
接着,根据端口号,我们可观察到,调用的为application-dev.yml文件的调用;也可以进行调用其他的文件进行测试,这样方便了我们在多环境中的快速使用。