前言
本文介绍Spring Boot中读取配置属性的几种方式,项目示例中用到的application.yml
和application.properties
定义如下:
@Value
@Value是比较常见的注入方式,功能强大但一般可读性较差。
@Value("str")
private String str; // 注入普通字符串
@Value("${hello}")
private String hello; // 注入配置属性
@Value("#{systemProperties['os.name']}")
private String systemPropertiesName; // 注入操作系统属性
@Value("#{ T(java.lang.Math).random() * 100.0 }")
private double randomNumber; //注入表达式结果
@Value("#{userBean.name}")
private String name; // 注入Bean属性
下面通过@Value注解获取定义在配置文件的属性值:
@SpringBootApplication
public class AttributeApplication {
private static final String SPRING_BOOT_HELLO = "spring-boot.hello";
@Value("${" + SPRING_BOOT_HELLO + "}")
private String hello;
/**
* 1. 通过@Value注解获取值
*/
public void getAttrByValueAnnotation() {
System.out.println("1. 通过@Value注解获取值: " + hello);
}
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(AttributeApplication.class, args);
AttributeApplication bean = applicationContext.getBean(AttributeApplication.class);
bean.getAttrByValueAnnotation