【问题标题】:Is it possible to have a @Value property defined by asterisk?是否可以有一个由星号定义的 @Value 属性?
【发布时间】:2020-12-15 16:24:39
【问题描述】:

例如:

@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*}"

【问题讨论】:

    标签: spring properties


    【解决方案1】:

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

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

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

    注意:我们应该使用@ConfigurationProperties 注释来读取多个键,在您的情况下,要读取Map&lt;String, String&gt;,我们必须在绑定其的类上使用@ConfigurationProperties 注释字段到一堆属性。所以在这里,@Value 不是绑定到Map 的正确用法,无论它是否具有星号字符。 Example For reading a Map

    即使带有星号,也可以读取Map&lt;String,String&gt;

    示例:

    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
    

    【讨论】:

      猜你喜欢
      • 2011-06-08
      • 2023-03-06
      • 2012-10-17
      • 2022-01-17
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      • 2021-12-13
      • 2015-12-11
      相关资源
      最近更新 更多