【发布时间】:2018-12-25 00:02:05
【问题描述】:
我在使用 spring 属性映射器时遇到了奇怪的问题。我有 yml 包含值列表。我想将其转换为构建应用程序的对象列表。所以,我使用了@ConfigurationProperties。有了这个,我可以映射简单的类型。当我将它用于复杂类型(对象列表)时,它失败了。也不例外,但是当我调试时值列表为零。请在下面找到 yml 和 java 文件。我尝试使用 spring 2.0.0,2.0.1,2.0.2,2.0.3 没有成功。任何人都可以解决它吗?
application.yml
acme:
list:
- name: my name
description: my description
- name: another name
description: another description
AcmeProperties.java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
@ConfigurationProperties("acme")
@PropertySource("classpath:configuration/yml/application.yml")
public class AcmeProperties {
private final List<MyPojo> list = new ArrayList<>();
public List<MyPojo> getList() {
return this.list;
}
static class MyPojo {
private String name;
private String description;
public String getName() {
return name;
}
public String getDescription() {
return description;
}
}
}
使用 setter 和 getter 方法:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@ConfigurationProperties(prefix = "acme")
@PropertySource("classpath:configuration/yml/application.yml")
public class AcmeProperties {
private List<MyPojo> list;
public List<MyPojo> getList() {
return list;
}
public void setList(List<MyPojo> list) {
this.list = list;
}
public static class MyPojo {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
}
这个类的用法:
@Autowired
public HomeController(AppProperties appProperties, AcmeProperties acmeProperties) {
this.appProperties = appProperties;
this.acmeProperties = acmeProperties;
}
【问题讨论】:
-
可以试试
public static class MyPojo,并把set方法放在上面。与list相同:使其成为非最终的,不要初始化它,并为其设置一个设置器 -
@MrSpoon,没有成功
-
我在 Spring Boot 应用程序中使用 setter 和 getter 尝试了您的代码,并且它有效......所以我怀疑问题出在这些类中。您不会手动或通过新创建和 AcmeProperties bean,对吗?春季启动版本?一个额外的信息。我省略了 @PropertySource("classpath:configuration/yml/application.yml") 我已将它放在资源文件夹中的 application.yml 中。您可以出于调试原因尝试吗?以防万一..
-
@Alexandros,我没有手动创建 AcmeProperties bean。我在我的控制器中自动连接了它。我用用法更新了我的问题,请检查。
-
@Alexandros,我使用的是 spring-boot 2.0.3。您可以在答案中发布您的更改吗?或用您的更改更新问题?
标签: java spring spring-boot yaml