首页 > 解决方案 > 是否可以有一个由星号定义的 @Value 属性?

问题描述

例如:

@Value("${a*}")
private Map<String, String> complexMap;

在我的application.yml

a*:
  "a": "a"
  "b": "b"
  "c": "c"

我越来越Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'a*' in value "${a*}"

标签: springproperties

解决方案


首先,@Value 用于绑定到一个键。但是,如果该密钥有任何星号,它仍然有效并且可以正确读取。

例如:我们可以test*: hello使用@Value 读取属性键。

@Value("${test1*}")
String greet; //hello

注意:我们应该使用@ConfigurationProperties注释来读取多个键,在您的情况下,要读取 a Map<String, String>,我们必须@ConfigurationProperties在将其字段绑定到一堆属性的类上使用注释。因此,无论它是否具有星号字符,都不@Value是绑定到 a 的正确用法。阅读地图的示例Map

即使有星号也可以阅读Map<String,String>

例子:

应用程序.yaml

test:
  comp*:
     a: a
     b: b

地图属性.java

@Component
@ConfigurationProperties(prefix = "test")
public class MapProperties {
    
Map<String, String> comp;

    public Map<String, String> getComp() {
        return comp;
    }

    public void setComp(Map<String, String> comp) {
        this.comp = comp;
    }
}

这里,comp* 属性绑定到MapProperties类中的这个 comp 字段。

MapProperties现在,您可以在需要的任何地方自动装配此类

@Autowired
MapProperties mapProperties;

您可以通过调用它的 getter 方法来获取属性值,例如:

mapProperties.getComp()

注意:如果没有这个前缀,它就不能工作,在我们的例子中,test。没有一些前缀,我们必须指定像@ConfigurationProperties(value= "comp*")

它抛出一个错误

  Configuration property name 'comp*' is not valid:

    Invalid characters: '*'
    Bean: mapProperties
    Reason: Canonical names should be kebab-case ('-' separated), lowercase alpha-numeric characters and must start with a letter

推荐阅读