一)@ConfigurationProperties简介
含义:该属性使强类型的Bean可以管理和验证应用程序的配置。可以说是@Value("${property}")注释的替代方法。
@Value("${property}")的缺点:当配置非常多时,如果引用的地方也非常多,需要在很多地方通过@Value注入属性。会造成代码重复和后期维护麻烦。因为@Value属于动态获取值,JavaBean属性不能用static修饰符修饰。
二)JavaBean基础属性绑定
application.yml配置如下:
server:
port: 9000
my:
bean:
id: 1
name: ouyangjun
或application.properties配置如下:
server.port=9000
my.bean.id=1
my.bean.name=ouyangjun
MyBeanProperties.java内容如下:
package com.oysept.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Component: 将该类注册成一个Bean
*/
@Component
@ConfigurationProperties(prefix = "my.bean")
public class MyBeanProperties {
private Integer id;
private String name;
public Integer getId() {return id;}
public void setId(Integer id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;