当前位置: 首页 > 知识库问答 >
问题:

Spring@ConfigurationProperties未映射对象列表

陆烨烁
2023-03-14
acme:
  list:
    - name: my name
      description: my description
    - name: another name
      description: another description
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;
        }
    }
}
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;
}

共有1个答案

詹亮
2023-03-14

问题是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

代码应该有效。

 类似资料: