我面临着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; }
问题是PropertySource仅支持属性文件,您无法从yml文件读取值。您可以像这样更新它:
PropertySource
yml
@Component @ConfigurationProperties("acme") @PropertySource("classpath:/configuration/yml/test.properties") class AcmeProperties {
配置/ yml / test.properties
acme.list[0].name=my name acme.list[0].description=my description acme.list[1].name=another name acme.list[1].description=another description
和代码应该工作。