1. 程式人生 > >springboot(6)從springboot配置檔案獲取值

springboot(6)從springboot配置檔案獲取值

1、配置檔案

在application.properties中新增測試資料

my.name = wxtx
my.age = 20
#my.desc的實際值為hello wxtx
my.desc = hello ${my.name}
my.host[0] = 127.0.0.1
my.host[1] = 127.0.0.2
my.host[2] = 127.0.0.3

2、獲取值

@Autowired
private Environment envir;

@Value("${my.desc}")
private String desc;

@Value("${my.age}")
private
Integer age; public void testProperty() throws Exception { //通過Environment獲取值 System.out.println(envir.getProperty("my.name")); //直接獲取指定值 System.out.println(age); System.out.println(desc); }

3、依賴注入值

@Component
@ConfigurationProperties("my")
public class TestProperties {

    // 自動將my.host[0]、my.host[1]、my.host[2]組裝成list物件注入
private List<String> host; public List<String> getHost() { return host; } public void setHost(List<String> host) { this.host = host; } }