本文讲解到的知识点是基于Springboot 2.1.5.RELEASE的版本。
首先先在resources目录下创建一个测试用的yml配置文件,内容如下:
PS:注意yml文件中key: value的冒号后面是有一个空格的
system:
user:
name: zjhuang
password: 123456
age: 25
一. @PropertySource + @Value
- 配置参数类代码
- @PropertySource: 为了告知springboot加载自定义的yml配置文件,springboot默认会自动加载application.yml文件,如果参数信息直接写在这个文件里,则不需要显式加载。
- @Value: 指定目标属性在yml’文件中的全限定名。
- @Component: 作用是将当前类实例化到spring容器中,相当于xml配置文件中的
<bean id="" class=""/>
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value = "classpath:test.yml")
public class YamlProperties {
@Value("${system.user.name}")
private String name;
@Value("${system.user.password}")
private String password;
@Value("${system.user.age}")
private int age;
// Setter...
// Getter...
// toStr