php小编西瓜带你深入探讨java中应用程序yml如何加载对象列表的问题。在java spring boot中,通过合理配置yml文件,可以实现对对象列表的加载,并在应用程序中灵活应用。接下来,让我们一起来掌握这一技巧,提升在spring boot开发中的实用性和效率。
问题内容
我有这个配置类:
@configuration
@configurationproperties(prefix = "house")
public class projectconfig{
private list<housetemplate> templates;
// getters and setters
}</housetemplate>
housetemplate 类:
public class housetemplate{
private string id;
private string description;
// getters and setters
}
这是我的应用程序-test.yml
house:
templates:
-
id: "colonial"
description: "colonial house template"
-
id: "cottage"
description: "cottage house template"
-
id: "apartment"
description: "apartment house template"
examplestring: hello
在我的测试类中,我有以下内容:
@runwith(springrunner.class)
@enableconfigurationproperties(value = projectconfig.class)
@testpropertysource("classpath:application-test.yml")
public class yamlapplicationcontextloadingspec {
@value("${examplestring}")
string example;
@autowired
projectconfig projectconfig;
@test
public void exampleshouldcontainhello(){
assertthat(example).isequaltoignoringcase("hello");
}
@test
public void appcontextcontainshousetemplates(){
list<housetemplate> housetemplates = projectconfig.gettemplates();
assertthat(housetemplates).isnotnull();
}
}</housetemplate>
关于 examplestring 的第一个测试通过,而第二个测试没有通过。为什么无法将yml映射到housetemplate列表中?
编辑
<artifactid>spring-core</artifactid><version>4.3.6.RELEASE</version><artifactid>spring-boot</artifactid><version>1.5.1.RELEASE</version><artifactid>junit</artifactid><version>4.12</version>
我知道它们真的很旧,我很想升级,但我不能……这就是我必须处理的。
解决方法
使用@configurationproperties从yml中读取后,可以将其注册为bean,然后可以通过applicationcontext获取。
@configuration
@configurationproperties(prefix = "house")
public class testconfig {
private list<housetemplate> templates;
@bean
public list<housetemplate> templates() {
return templates;
}
// getter and setter
}
@restcontroller
@requestmapping("/api/test")
public class testcontroller {
@autowired
private applicationcontext applicationcontext;
@getmapping("get")
@suppresswarnings("unchecked")
public list<housetemplate> get() {
return (list<housetemplate>) applicationcontext.getbean("templates");
}
}
</housetemplate></housetemplate></housetemplate></housetemplate>
如果你不想注册为bean,也可以将变量声明为静态。
这是一个示例。
@Configuration
@ConfigurationProperties(prefix = "House")
public class TestConfig {
private static List<housetemplate> templates;
public static List<housetemplate> get() {
return templates;
}
public List<housetemplate> getTemplates() {
return templates;
}
public void setTemplates(List<housetemplate> templates) {
TestConfig.templates = templates;
}
}
@RestController
@RequestMapping("/api/test")
public class TestController {
@GetMapping("get")
public List<housetemplate> get() {
return TestConfig.get();
}
}
</housetemplate></housetemplate></housetemplate></housetemplate></housetemplate>
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










