我无法从YAML文件注入Map <string,string =“”>

时间:2019-03-22 13:05:01

标签: spring-boot yaml

我的YAML文件中具有以下属性:

request-topic:
  topics:
    IMPORT_CHARGES: topic-name-1
    IMPORT_PAYMENTS: topic-name-2
    IMPORT_CATALOGS: topic-name-3

这堂课

@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "topic-properties")
public class TopicProperties {
    private Map<String, String> topics = new HashMap<>();

    public String getTopicNameByType(String type){
        return topics.get(type);
    }
}

但是当我自动连接这些属性时,我得到的是空地图:

@Service
public class TopicRouterImpl implements TopicRouter {

    private final TopicProperties topics;

    public TopicRouterImpl(TopicProperties topics) {
        this.topics = topics;
    }

    @PostConstruct
    public void init(){
        topics.getTopicNameByType("IMPORT_CHARGES");
    }

    @Override
    public String getTopicName(MessageType messageType) {
        return topics.getTopicNameByType(messageType.name());
    }
}

1 个答案:

答案 0 :(得分:1)

这是由于yaml文件中的名称不匹配,因此应等于指定的前缀topic-properties。像这样:

topic-properties:
  topics:
    IMPORT_CHARGES: topic-name-1
    IMPORT_PAYMENTS: topic-name-2
    IMPORT_CATALOGS: topic-name-3