读取配置文件内容三种方式:

  • @Value
  • Environment
  • @ConfigurationProperties
1
2
3
4
5
6
7
8
9
10
11
12
#对象形式
user:
name: zhangsan
age: 23
address: xian
#数组格式
object:
- JAVA #- 和 数据用空格分离
- 大数据
- 前端
#字面量
name: yamiedie

@Value方式

需要配置SpEL表达式,${一级属性名.二级属性名}

image-20220806160931458

  • 对象形式

    1
    2
    @Value("${server.port}")
    private int port;
  • 数组形式

    1
    2
    @Value("${object[1]}")
    private String object;
  • 普通形式

    1
    2
    @Value("${name}")
    private String name;

Environment方式

首先要进行Bean注入

1
2
@Autowired
private Environment env;

SpringBoot会通过数据装配的方式把数据全部装到这一个对象里。

使用getProperty,方法获取属性值。

示例:

1
2
3
System.out.println(env.getProperty("name"));
System.out.println(env.getProperty("server.port"));
System.out.println(env.getProperty("object[1]"));

@ConfigurationProperties方式

使用@ConfigurationProperties注解绑定配置信息到封装类

例如:

Yaml配置文件

1
2
3
4
5
6
7
8
9
10
datasource:
driver: com.driver.cj.mysql
url: localhost
username: root
password: root
user:
- me
- you
- he
- she

如果有警告,可以在pom文件中,加入如下依赖。【在classpath中没有发现SpringBoot 配置注解处理器】

image-20220806163710093

1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

注意:

  • 必须加@Component注解,注入到Spring容器中。
  • prefix属性为一级属性名
  • 类中必须有Getter和Setter方法,否则无法注入.
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
@Component
@ConfigurationProperties(prefix = "datasource")
public class Mydatasource {
private String driver;
private String url;
private String username;
private String password;
private String[] user;

public String getDriver() {
return driver;
}

public void setDriver(String driver) {
this.driver = driver;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String[] getUser() {
return user;
}

public void setUser(String[] user) {
this.user = user;
}

@Override
public String toString() {
return "Mydatasource{" +
"driver='" + driver + '\'' +
", url='" + url + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}

__END__