3 回答

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
這個(gè)說法是錯(cuò)誤static ConfigurationUnit configurationUnit = new ConfigurationUnit(); 的 你不應(yīng)該創(chuàng)建對(duì)象
Spring 僅將屬性注入到由應(yīng)用程序上下文處理的 bean 中,并且 spring 創(chuàng)建帶有注釋的類的 bean@ Configuration
配置單元
@Configuration
@ConfigurationProperties("example-unit")
public class ConfigurationUnit {
public List<String> confiList;
public List<String> getConfiList() {
return this.confiList;
}
}
DemoApplication在 spring boot main 中從 applicationcontext 獲取 bean 并從中獲取列表對(duì)象
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(DemoApplication.class, args);
ConfigurationUnit unit = context.getBean("configurationUnit"):
System.out.print(unit. getConfiList());
}
}

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
將您的列表放在prefix.property下。在你的情況下example-unit.confi-list:
。通常為您的屬性提供一個(gè)設(shè)置器:setConfiList(List<String> strings)
. 但是由于您已經(jīng)將它初始化為空數(shù)組列表,所以這個(gè) setter 已經(jīng)過時(shí)了。還有建議將 Enable-annotation 添加到 Application 類:
應(yīng)用程序類應(yīng)該有 @EnableConfigurationProperties 注釋

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超4個(gè)贊
這是有關(guān)Spring Bboot 配置綁定如何工作的參考。
專門針對(duì)您的問題,這是實(shí)現(xiàn)您的目標(biāo)的應(yīng)用程序示例:
應(yīng)用程序.yml
example-unit:
confiList:
- string1
- string2
- hello22
來源
@SpringBootApplication
@EnableConfigurationProperties(ConfigurationUnit.class)
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
ConfigurationUnit configurationUnit = context.getBean(ConfigurationUnit.class);
System.out.println(configurationUnit.getConfiList());
}
}
@ConfigurationProperties("example-unit")
public class ConfigurationUnit {
public List<String> confiList = new ArrayList<>();
public List<String> getConfiList() {
return this.confiList;
}
}
添加回答
舉報(bào)