配置文件的属性注入java类
一、Spring中的方式
application.properties
- 如果配置文件是application.properties,项目启动时会自动扫描到,直接通过@Value注入到bean中即可。例子如下:
(1) application.properties
xxx.id=007
xxx.name=小明来了
xxx.sex=男孩子
(2)实体类 XxxConfig.java
@Component
public class XxxConfig {
@Value("${xxx.id}")
private Integer id;
@Value("${xxx.name}")
private String name;
@Value("${xxx.sex}")
private String sex;
//此处省略 getter,setter,toString
(3)测试类输出测试下
自定义properties属性
- 自定义properties配置文件项目启动不会加载,需要通过@PropertySource注解
xxx2.properties
xxx2.id=0072
xxx2.name=小明来了2
xxx2.sex=男孩子2
Xxx2Config.java
@Component
@PropertySource("classpath:xxx2.properties")
public class Xxx2Config {
@Value("${xxx2.id}")
private Integer id;
@Value("${xxx2.name}")
private String name;
@Value("${xxx2.sex}")
private String sex;
//此处省略 getter,setter,toString
二、boot中的方式
上面通过Spring的配置方式,如果属性特别多,配置起来工作量大且容易出错,boot中有了更好的方式来避免;
通过@ConfigurationProperties注解来配置前缀,如下示例:
BootConfig.java
@Component
@PropertySource("classpath:boot.properties")
@ConfigurationProperties(prefix = "gg") //boot为前缀
public class BootConfig {//属性名要与配置文件后缀一致
private int id;
private String name;
private String sex;
//此处省略 getter,setter,toString
boot.properties
gg.id=009
gg.name=小明来了boot
gg.sex=男孩子boot
源码已上传 https://gitee.com/shuaidawang/SpringBoot