读取application.yml中定义属性值的三种方式

  • 时间:
  • 浏览:
  • 来源:互联网

name: zhangsan

person:
  name: lisi
  age: 12

address:
  - beijing
  - shanghai

msg1: 'hello \n world' # \n会被原样输出,不会转义
msg2: "hello \n world"  # \n 会被转义

方式一

@Value("${name}")
private String name;
@Value("${person.name}")
private String personName;
@Value("${address[0]}")
private String address;
@Value("${msg1}")
private String msg1;
@Value("${msg2}")
private String msg2;

方式二

@Autowired
private Environment env;

// 获取值
env.getProperty("name")

方式三

定义一个用户映射属性的实体

@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

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

// 使用
@Autowired
private Person person;

 

本文链接http://www.dzjqx.cn/news/show-617348.html