今天我们一起来学习一下如何自定义配置文件,在这之前我们可能会把配置项写在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();
}
}
启动入口类,通过浏览器访问: