是否可以使用星号定义@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*}"

解决方法

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

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

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

注意:我们应该使用@ConfigurationProperties批注来读取多个键,在这种情况下,要读取Map<String,String>,我们必须使用@ConfigurationProperties批注在将其字段绑定到一堆属性的类上。因此,这里@Value并不是绑定到Map的正确用法,无论它是否带有星号字符。 Example For reading a Map

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

示例:

application.yaml

test:
  comp*:
     a: a
     b: b

MapProperties.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