3 回答
TA贡献1835条经验 获得超7个赞
这个说法是错误static ConfigurationUnit configurationUnit = new ConfigurationUnit(); 的 你不应该创建对象
Spring 仅将属性注入到由应用程序上下文处理的 bean 中,并且 spring 创建带有注释的类的 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 并从中获取列表对象
@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贡献1827条经验 获得超4个赞
这是有关Spring Bboot 配置绑定如何工作的参考。
专门针对您的问题,这是实现您的目标的应用程序示例:
应用程序.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;
}
}
添加回答
举报