目录
springboot
读取配置文件中的数据
在 springboot
框架里面对一些系统配置或者常量配置必须要在名字为 application
文件里配置 ,文件类型可以为后缀为 .properties
或者 .yml
形式
其实无论是 properties
文件还是 yml
文件,他们的本质是相同的,即都是键值对,只不过写法不一样而已
下面介绍几种最常用的读取配置文件中数据的方法
springboot
读取配置文件中的数据方法
使用 @Value
注解
application.properties
配置文件
demo.name=Name
demo.age=18
Java
代码
@RestController
public class GatewayController {
@Value("${demo.name}")
private String name;
@Value("${demo.age}")
private String age;
@RequestMapping(value = "/gateway")
public String gateway() {
return "get properties value by ''@Value'' :" +
// 使用 @Value 注解读取
" name=" + name +
" , age=" + age;
}
}
使用 Environment
application.properties
配置文件
demo.sex=男
demo.address=山东
Java
代码
@RestController
public class GatewayController {
@Autowired
private Environment environment;
@RequestMapping(value = "/gateway")
public String gateway() {
return "get properties value by ''@Value'' :" +
// 使用 Environment 读取
" , sex=" + environment.getProperty("demo.sex") +
" , address=" + environment.getProperty("demo.address");
}
}
使用 @ConfigurationProperties
注解
config.properties
配置文件
demo.phone=10086
demo.wife=self
创建 Java
实体类
@Component
@ConfigurationProperties(prefix = "demo")
@PropertySource(value = "config.properties")// 指定要读取哪一个配置文件
public class ConfigBeanProp {
private String phone;
private String wife;
// get/set 方法省略......
}
Java
代码
@RestController
public class GatewayController {
@Autowired
private ConfigBeanProp configBeanProp;
@RequestMapping(value = "/gateway")
public String gateway() {
return "get properties value by ''@Value'' :" +
// 使用 @ConfigurationProperties 注解读取
" phone=" + configBeanProp.getPhone() +
" , wife=" + configBeanProp.getWife();
}
}