文章目录
配置文件
SpringBoot的配置文件,有三种格式
1.properties
2.yaml
3.yml
(yaml的简写)
事实是:SpringBoot只支持3个文件
1.application.prperties
2.application.yaml
3.application.yml
如果项目中同时存在properties
和yml
配置文件,properties
的优先级更高,同时存在时,两个文件都生效,如果两个文件中都包含同一个配置,以properties
为主。
配置文件的格式
properties
properties
:key value的形式,以=分割,key的格式建议是小写,单词之间使用.
分割
获取配置项
# 自定义配置
demo.key1 = hello,properties
@RestController
public class PropertiesController {
// 读取配置文件
@Value("${demo.key1}")
private String key1;
@RequestMapping("/readKey")
public String readKey(){
return "读取到的配置项key1: "+key1;
}
}
yml
冒号后面一定要加空格,值的前面的空格不可以省略。
server:
port: 9090
yml
连接数据库
# 数据库相关配置
spring:
datasource:
url: jdbc:mysql://127.0.0.1/mycnblog?characterEncoding=utf8
username: root
password: 123456
获取配置项
demo:
key1: hello,yml
@RestController
public class YmlController {
@Value("${demo.key1}")
public String key1;
@RequestMapping("/readYml")
public String readYml(){
return key1;
}
}
单双引号区别
配置对象
student:
id: 18
name: zhangsan
age: 12
@RestController
public class YmlController {
@PostConstruct
public void init(){
System.out.println("student: " + student);
}
@Autowired
public Student student;
}
@Component
@ConfigurationProperties(prefix = "student")
@Data
public class Student {
private Integer id;
private String name;
private Integer age;
}
配置集合
dbtypes:
name:
-