SpringBoot-配置文件详解之自定义配置文件

今天我们一起来学习一下如何自定义配置文件,在这之前我们可能会把配置项写在application.properties或者application.yml中。这是springboot默认读取的配置文件,但是有时候我们需要自定义配置文件用于配置特定需求的配置项。比如我们在classpath下建一个test.properties文件:

然后将该配置文件配置项的值用一个javabean来接收: 

@Component
@PropertySource(value = "classpath:test.properties", encoding = "UTF-8")
@ConfigurationProperties(prefix = "custom.properties")
public class CustomPropertiesFile {

  @Value("${year:2018}")
  private Integer year;

  @Value("${month:1}")
  private Integer month;

  public Integer getYear() {
    return year;
  }

  public void setYear(Integer year) {
    this.year = year;
  }

  public Integer getMonth() {
    return month;
  }

  public void setMonth(Integer month) {
    this.month = month;
  }

}

注意:

SpringBoot1.4及之前的版本中,要实现自定义properties配置文件与JavaBean的映射,只需要在配置文件对应的JavaBean上增加@ConfigurationProperties(locations="classpath:test.properties", prefix="custom.properties")这个注解,并在项目启动类上增加@EnableConfigurationProperties启动配置即可。但是在之后的版本中,@ConfigurationProperties注解不再提供locations属性,所以无法实现映射。

解决这个问题,只需要在配置文件对应的JavaBean上增加:

  • @Component
  • @ConfigurationProperties(prefix = "custom.properties")
  • @PropertySource(value = "classpath:test.properties", encoding = "UTF-8") 

这三个注解即可,也不需要在项目启动类上增加@EnableConfigurationProperties这个注解(如果此时在启动类上将配置类添加到@EnableConfigurationProperties注解里,则会报错。然后我们写一个简单的controller类测试一下:

@RestController
@RequestMapping("/test/*")
public class CustomPropertiesFileController {

  @Autowired
  private CustomPropertiesFile file;

  @RequestMapping("getProperties")
  public String getProperties() {
    return file.getYear() + ":" + file.getMonth();
  }
}

启动入口类,通过浏览器访问:

源代码地址:https://gitee.com/chengab/SpringBoot/tree/master/springboot/src/main/java/com/study/springboot/properties

参考博客: SpringBoot非官方教程 | 第二篇:Spring Boot配置文件详解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值