依赖

1
2
3
4
5
6
<!-- 该依赖功能为在书写yml时有提示 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

配置文件数据

1
2
3
4
person:
name: wp
age: 18
str: 这是字符串
方式一

通过@Value注解(可不创建实体类)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

@Service
@PropertySource(value = "application.yml")
public class DemoService {

@Value("${person.str}")
private String str;

public String getConfigCes(){
return str;
}

}

注:@PropertySource用来指定要获取的配置文件

方式二

通过@ConfigurationProperties注解(创建实体类)

  • 实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "person")
@PropertySource(value = "application.yml")
public class Person {

private String name;
private String age;
private String str;

@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
", str='" + str + '\'' +
'}';
}
}

注:该实体类需要注册进容器

  • 测试类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import com.simplemw.model.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DemoService {

@Autowired
private Person person;

public String getConfigCes(){
return person.toString();
}

}