springboot实战原理分析笔记(二)-读取配置文件

配置文件 支持 .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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值