Spring 是否可以使用星号定义@Value属性?

Spring 是否可以使用星号定义@Value属性?,spring,properties,Spring,Properties,例如: @Value("${a*}") private Map<String, String> complexMap; 我得到的原因是:java.lang.IllegalArgumentException:无法解析值“${a*}”中的占位符“a*”首先,@value用于绑定到单个键。但是,如果该键有任何星号,它仍然有效&读取正确 例如:我们可以使用@Value读取属性键test*:hello @Value("${test1*}") Strin

例如:

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

我得到的
原因是:java.lang.IllegalArgumentException:无法解析值“${a*}”中的占位符“a*”

首先,@value用于绑定到单个键。但是,如果该键有任何星号,它仍然有效&读取正确

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

@Value("${test1*}")
String greet; //hello
注意:我们应该使用
@ConfigurationProperties
注释来读取多个键,在您的例子中,要读取
映射
,我们必须在将其字段绑定到一组属性的类上使用
@ConfigurationProperties
注释。因此,在这里,
@Value
不是绑定到
映射
的正确用法,不管它是否具有星号字符

即使使用星号,也可以读取
Map

示例:

应用程序.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;
    }
}
您可以通过调用其getter方法来获取属性值,如下所示:

mapProperties.getComp()
注意:在我们的示例中,如果没有此前缀,test,它将无法工作。如果没有前缀,我们必须指定like
@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

首先,@Value用于绑定到单个键。但是,如果该键有任何星号,它仍然有效&读取正确

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

@Value("${test1*}")
String greet; //hello
注意:我们应该使用
@ConfigurationProperties
注释来读取多个键,在您的例子中,要读取
映射
,我们必须在将其字段绑定到一组属性的类上使用
@ConfigurationProperties
注释。因此,在这里,
@Value
不是绑定到
映射
的正确用法,不管它是否具有星号字符

即使使用星号,也可以读取
Map

示例:

应用程序.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;
    }
}
您可以通过调用其getter方法来获取属性值,如下所示:

mapProperties.getComp()
注意:在我们的示例中,如果没有此前缀,test,它将无法工作。如果没有前缀,我们必须指定like
@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