配置文件 支持 .properties或.yml 文件
1. 读取配置文件的值:
- @Value("${键名称}") #默认必须要有配置项,值可以为空 也可以通过@Value("${键名称:默认值}") 指定默认值 。
- 注入Environment
注意:配置文件里面也可以引用配置
name=springboot
app.Name=this is ${name}
2. 配置文件的路径
- 配置文件的路径一般默认名称为application.properties,在classath根目录,或者classpath:/config, file:/ file:/config
- 指定配置文件名称:
1.通过启动参数指定配置文件目录
--spring.config.name=app.properties/app 文件扩展名可以省略
2.通过启动参数
--spring.config.location=classpath:conf/app.properties,file:E:\temp\a.properties #多个可以用, 分割开
3. 通过代码设置 (属性要有get set 方法)
1.在配置类上加上
@PropertySource(value={"classpath:conf/jdbc.properties", "file:/E:\\temp\\jdbc.properties"})
2.或者在配置类上加上
@PropertySource("classpath:conf/jdbc.properties")
@PropertySource("file:/E:\\temp\\jdbc.properties")
3.或者在配置类上加上
@PropertySources(value = {@PropertySource("classpath:conf/jdbc.properties"),@PropertySource("file:/E:\\\\temp\\\\jdbc.properties")})
4.或者在配置类上加上,这个一般要加上@EnableConfigurationProperties
@ConfigurationProperties(prefix = “ds”,locations=“classpath:conf/ds.properties”)
3. 通过数组、集合的配置设置 (属性要有get set 方法)
ds.hosts[0]=192.168.1.1
ds.hosts[1]=192.168.1.2
ds.hosts[2]=192.168.1.3
name[index]=value