springboot(6)从springboot配置文件获取值

1、配置文件

在application.properties中添加测试数据

1
2
3
4
5
6
7
my.name = wxtx
my.age = 20
#my.desc的实际值为hello wxtx
my.desc = hello ${my.name}
my.host[0] = 127.0.0.1
my.host[1] = 127.0.0.2
my.host[2] = 127.0.0.3

2、获取值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Autowired
private Environment envir;

@Value("${my.desc}")
private String desc;

@Value("${my.age}")
private Integer age;

// 不存在的值设置null
@Value("${my.history:#{null}}")
private String history;

public void testProperty() throws Exception {
//通过Environment获取值
System.out.println(envir.getProperty("my.name"));
//直接获取指定值
System.out.println(age);
System.out.println(desc);
//输出null
System.out.println(history);
}

3、依赖注入值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Component
@ConfigurationProperties("my")
public class TestProperties {

// 自动将my.host[0]、my.host[1]、my.host[2]组装成list对象注入
private List<String> host;
public List<String> getHost() {
return host;
}
public void setHost(List<String> host) {
this.host = host;
}

}
>