我无法在Spring Boot中从yaml中注入Map

25 浏览
0 Comments

我无法在Spring Boot中从yaml中注入Map

我在application.yaml文件中有以下数值:\nimport-charge-fields:\n 4: billDate\n 1001: validUntil\n 7: totalAmount\n 24: purpose\n\n然后我尝试在服务中注入它:\n

    @Value("${import-charge-fields}")
    private Map fields;

\n但是我得到了异常:\n

\nCaused by: java.lang.IllegalArgumentException: 无法解析值\"${import-charge-fields}\"中的占位符 \'import-charge-fields\'\n

\n我尝试了以下方法:\ncharge:\n hz: 123\n fields:\n 4: billDate\n 1001: validUntil\n 7: totalAmount\n 24: purpose\n\n以及\n

@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "charge")
public class ChargeFields {
   private String hz;
   private Map fields;
}

\n以及\n

@Value("${charge.hz}")
private String hz;
@Value("${charge.fields}")
private Map fields;

\n但是都没有起作用。

0
0 Comments

在Spring Boot中无法从yaml文件中注入Map的问题可能是由于yaml文件中的字段名不合法导致的。yaml文件中的字段名不能为数字,而应该为字符串。解决方法是在字段名前添加引号。

以下是正确的示例:

import-charge-fields:

"4": billDate

"1001": validUntil

"7": totalAmount

"24": purpose

以上的Java代码都是有效的,并且应该可以正常工作。

0
0 Comments

问题原因:在使用Spring Boot的yaml文件中注入Map时出现问题。经过多次尝试后,发现问题出现在Set方法上。必须实现setFields()方法。

解决方法:实现setFields()方法。

0