SpringBoot 获取配置文件内容

在一些业务需求上,我们需要获取配置文件的某些配置内容,达到某种功能,
那么如何获取spingboot的配置参数内容呢?

最常见的有几种方式

application.yml

COPY
1
2
3
4
5
6
7
8
# 应用名称
spring:
application:
name: springboot

# 应用服务 WEB 访问端口
server:
port: 8080

方式一:@Value注解

获取少量的配置,可以直接使用@Value注解获取

SpringbootApplicationTests.java

COPY
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

@SpringBootTest
class SpringbootApplicationTests {

@Value("${spring.application.name}")
public String name;

@Value("${server.port}")
public String port;

@Test
void contextLoads() {
System.out.println("Application_Name:"+name+"\nPort:"+port);
}

}

方式二:Environment接口

SpringbootApplicationTests.java

COPY
1
2
3
4
5
6
7
8
9
10
11
12
13
@SpringBootTest
class SpringbootApplicationTests {

@Autowired
public Environment env;

@Test
void contextLoads() {
System.out.println("Application_Name:"+env.getProperty("spring.application.name")
+"\nPort:"+env.getProperty("server.port"));
}

}

方式三:@ConfigurationProperties注解

COPY
1
2
3
4
5
6
7
8
9
10
11
12
13
# 应用名称
spring:
application:
name: springboot
# 应用服务 WEB 访问端口
server:
port: 8080

# 自定义的
custom:
name: Steve
age: 20

COPY
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

@Component
@ConfigurationProperties(prefix = "custom")
@SpringBootTest
class SpringbootApplicationTests {

private String name;

private String age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAge() {
return age;
}

public void setAge(String age) {
this.age = age;
}

@Test
void contextLoads() {
System.out.println("Name:"+getName()+"\nAge:"+getAge());
}

}
Authorship: Lete乐特
Article Link: https://blog.imlete.cn/article/SpringBoot-Get-Config.html
Copyright: All posts on this blog are licensed under the CC BY-NC-SA 4.0 license unless otherwise stated. Please cite Lete乐特 's Blog !