springboot默认的全局配置文件名为application.properties或者application.yml,在application.properties加载之前会先加载一个bootstrap的全局文件,可以利用它进行配置文件的动态修改。
自定义属性及引用
blog.address=https://blog.lqdev.cn
blog.author=oKong
@RestController
public class DemoController {
@Value("${blog.address}")
String address;
@Value("${blog.author}")
String author;
属性引用
blog.address=https://blog.lqdev.cn
blog.author=oKong
blog.desc=${blog.author},${blog.address}
由于springboot在读取properties文件时,使用的是PropertiesPropertySourceLoader类进行读取,默认读取的编码是ISO 8859-1,故在默认的配置文件中使用中文时,会出现乱码,此时可以将中文转成Unicode编码或者使用yml配置格式(默认就支持utf-8),再不济可以将作为配置写入到一个自定义配置文件,利用@PropertySource注解的encoding属性指定编码
自定义配置文件
利用@PropertySource注解既可以引入配置文件,需要引入多个时,可使用@PropertySources设置数组,引入多个文件。
@SpringBootApplication
@PropertySource(value="classpath:my.properties",encoding="utf-8")
public class Chapter3Application {
public static void main(String[] args) {
SpringApplication.run(Chapter3Application.class, args);
}
}
配置绑定对象
利用@ConfigurationProperties属性,在多某个配置项属于某一配置时,可以对应到一个实体配置类中。
配置文件:
config.code=code
config.name=趔趄的猿
config.hobby[0]=看电影
config.hobby[1]=旅游
实体类:
@Component
//@EnableConfigurationProperties(value= {Config.class})
@ConfigurationProperties(prefix="config")
@Data
public class Config {
String code;
String name;
List<String> hobby;
}
这里可直接加入@Component使其在启动时被自动扫描到,或者使用@EnableConfigurationProperties注解注册此实体bean.
其次,在引入@ConfigurationProperties时,IDE会提示你引入spring-boot-configuration-processor依赖,前面提到,在自定义属性时,创建additional-spring-configuration-metadata.json可进行属性提示,而此依赖功能类似,会编译时自动生成spring-configuration-metadata.json文件,此文件主要给IDE使用,用于提示使用。添加后在配置文件点击属性时,会自动跳转到对应绑定的实体类中
参考:https://blog.lqdev.cn/2018/07/14/springboot/chapter-third/
网友评论