Springboot自定义配置类
文章目录
1. 简介
在开发过程中需要将一些可配置的东西抽出来放到配置文件中统一管理,即方便开发也方便统一管理,抽取到配置文件中的配置内容是需要读取出来在程序中使用的,下面介绍几种获取配置的方式。
2. @Value方式获取参数
在Spring程序中是可以通过@Value注解来获取配置文件中的参数的。
@Value("${my.config.name}")
private String name;
@Value("${my.config.age}")
private Integer age;
还可以指定默认值,如果配置项没有在配置文件中配置时,就会使用默认值。
@Value("${my.config.name:张三}")
private String name;
3. 自定义配置类
当一组有关系的配置项或者数据在一起时,或者配置数据很多时,使用@Value的方式会比较麻烦,每一个需要的地方都需要重复的使用@Value进行读取配置。所以这时我们需要使用自定义配置类来将一组数据封装到一个实体类中。
3.1 定义一个配置类
@Data
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "my.config")
public class MyConfigProperties {private String name;private String address;private Integer age;private List<String> interest;private Map<String, Integer> exam;private List<Role> roles;@Datapublic static class Role {private Integer roleId;private String roleName;}
}
以上配置类配置了字符串类型、整型、集合、Map、对象多种类型的配置。考虑到了常用的几种情况
3.2 yml配置文件定义属性
根据配置类在配置文件中配置属性
my.config:name: "张三2"address: "北京"age: 18interest:- 打球- 旅游exam:"期中": 100"期末": 100roles:- roleId: 1roleName: 子女- roleId: 2roleName: 学生
3.3 properties配置文件定义属性
如果是properties配置文件,则配置方式如下:
my.config.name="张三1"
my.config.address="北京"
my.config.age=18
my.config.interest[0]="打球"
my.config.interest[1]="旅游"my.config.roles[0].roleId=1
my.config.roles[0].roleName="学生"my.config.exam["期中"]=100
my.config.exam["期末"]=100
3.4 使用配置类
在需要使用配置类的地方,直接注入即可。
@Autowired
private MyConfigProperties myConfigProperties;
4. 配置文件编码问题
springboot在读取.properties配置文件时会出现乱码的问题,读取application.properties文件时,编码默认是ISO-8859-1,所以直接配置中文一定会乱码。而yml配置文件则是以UTF-8加载,则不会出现乱码的问题。
所以如果想解决乱码的问题可以直接使用yml配置文件进行配置,或者使用自定义的properties配置文件,同时在配置类上使用@PropertySource注解指定读取的配置文件以及编码类型加载。
@Data
@Slf4j
@Configuration
@PropertySource(value = "classpath:application-config.properties", encoding = "UTF-8")
@ConfigurationProperties(prefix = "my.config")
public class MyConfigProperties {private String name;private String address;private Integer age;private List<String> interest;private Map<String, Integer> exam;private List<Role> roles;@Datapublic static class Role {private Integer roleId;private String roleName;}
}
或者对乱码的数据进行编解码重读,例如name字段数据乱码了,则可以通过以下方式重新读取name的UTF-8的值:
System.out.println(new String(name.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
5. 总结
在开发时使用自动配置类是非常方便的一种手段,可以方便的将数据进行统一注入。