springboot yml配置文件注入值 - ZaneEli - 博客园

1.编写javabean:

?

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

package com.example.springboot.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.stereotype.Component;

import java.util.Date;

import java.util.List;

import java.util.Map;

/**

* @PROJECT_NAME:spring-boot-01-hello

* @Data:2019/10/7

@ConfigurationProperties 告诉SpringBoot将配置文件中对应属性的值,映射到这个

组件类中,进行一一绑定

* prefix = "emp":配置文件中的前缀名,哪个前缀与下面的所有属性进行一一映射

* 2、@Component 必须将当前组件作为SpringBoot中的一个组件,才能使用容器提供的

*/

@Component

@ConfigurationProperties`(prefix = "emp"`)

public class Emp {

private String lastName;

private Integer age;

private Double salary;

private Boolean boss;

private Date birthday;

private Map map;

private List list;

private Forte forte;

@Override

public String toString() {

return "Emp{" +

"lastName='" + lastName + '\`'' +`

", age=" + age +

", salary=" + salary +

", boss=" + boss +

", birthday=" + birthday +

", map=" + map +

", forte=" + forte +

'}'`;`

}

get and set.....

}

 2.yml文件

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

server:

port: 8088

# emp配置数据

emp:

lastName: Zane

age: 28

salary: 2000

boss: True

birthday: 2019/09/09

map:

key1: value1

key2: value2

list:

- one

- two

- three

forte:

name: java

time: 8

 通过@ConfigurationProperties(prefix = "emp")可以将yml文件与bean文件关联起来

注意:

1.emp上方出现如下提示

 我们只需导入配置文件处理器即可

1 <!--导入配置文件处理器,在编写配置文件时就会提示 在pom.xml-->
2 <dependency>
3 <groupId>org.springframework.boot</groupId>
4 <artifactId>spring-boot-configuration-processor</artifactId>
5 <optional>true</optional>
6 </dependency>


Original url: Access
Created at: 2020-08-20 13:09:10
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论