SpringBoot读取yml配置的几种方式

1.@Value

server:
  port: 8081

取值代码:

@Value("${server.port}")
public String port;	

2.@ConfigurationProperties

如果需要一个JavaBean 来专门映射配置的话,我们一般会使用@ConfigurationProperties来读取.

student:
    age: 18
    name: mysgk

javabean:

@Component
@ConfigurationProperties(prefix = "student")
public class Student {

    private String name;

    private Integer age;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

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

使用@ConfigurationProperties,需要配置一个prefix (前缀) 参数, 即写上 key 就可以了.

3.@Environment

test:
    msg: aaa
    @Autowired
    private Environment env

    @RequestMapping(value = "index2", method = RequestMethod.GET)
    public String index2() {
        System.out.println(env.getProperty("test.msg"));
        return "The Way 2 : "+ env.getProperty("test.msg");
    }
}	    

上一篇:unity shader 热扭曲 (屏幕后处理)


下一篇:js阻止冒泡事件发生实例