作用:用来自动读取配置
用法如下:
1 PhoneProperties类内容如下:
package com.gm.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "phone")
public class PhoneProperties {
private String type;
private float price;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
查找application.yml文件中phone.type,将对应的value赋值给type,将phone.price对应的value赋值给price
2 application.yml文件内容如下:
phone:
type: oppo
price: 3000
3 SpringBoot并不会创建PhoneProperties实例,在使用时,可以通过@EnableConfigurationProperties注解来创建实例,并注入到IOC容器中,如下
package com.gm.config.configure;
import com.gm.config.bean.Phone;
import com.gm.config.properties.PhoneProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(PhoneProperties.class)
public class DemoConfig {
@Autowired
private PhoneProperties phoneProperties;
@Bean
public Phone phone() {
return new Phone(phoneProperties.getType(), phoneProperties.getPrice());
}
}
PS:当然,也可以直接在PhoneProperties类上加上@Component注解,让SpringBoot将PhoneProperties实例注入到IOC容器中