简体   繁体   English

如何从 Spring 文件中的 YAML 文件中读取 Object 的数组

[英]How to Read Array of Object from YAML file in Spring

We are working on Spring based application which needs to access and read certain credentials stored in the yaml file which use the format below:我们正在开发基于 Spring 的应用程序,该应用程序需要访问和读取存储在 yaml 文件中的某些凭据,该文件使用以下格式:

#yaml file content
...
secrets: username1:pw1, username2:pw2
...

we load the yaml file using PropertySource annotation like this我们使用这样的 PropertySource 注释加载 yaml 文件

@PropertySources({
        @PropertySource(value = "file:/someSecretPath/secrets.yaml", ignoreResourceNotFound = true) // secret yaml file
})

I have tried using the following code to parse it into array of map object since it is a list contains 2 object type,我尝试使用以下代码将其解析为 map object 的数组,因为它是一个包含 2 个 object 类型的列表,

@Repository
public class getSecretClass {
  
    @Value("${secrets}")
    private Map<String,String>[] credentials;
}

but it fails with this error:但它失败并出现此错误:

... 'java.lang.string' cannot be converted into java.lang.map[] ....

On the other hand, I tested reading from simple string array like this one:另一方面,我测试了从像这样的简单字符串数组中读取:

#yaml file content
...
secrets: text1, text2
...

and the code below would work with no issue:并且下面的代码可以正常工作:

@Repository
public class getSecretClass {
  
    @Value("${secrets}")
    private String[] credentials;

    ...
    private someReadSecretMethod(){
       System.out.println( credentials[0] );
    } 

}

it will print "text1" as expected.它将按预期打印“text1”。 But we do need to store the credentials as pairs in my use case, a plain text would not work for me.但是我们确实需要在我的用例中将凭据成对存储,纯文本对我不起作用。

Any suggestion or advice would be much appreciated !任何建议或意见将不胜感激!

Why not do something easier on the eyes, easier to program if not a little verbose:如果不是有点冗长,为什么不做一些对眼睛更容易,更容易编程的事情:

secrets:
- username: username1
  password: pwd1
- username: username2
  password: pwd2

Have a class for your secret:为您的秘密准备一个 class:

public class Secret {
  private String username;
  private String password;

  public String toString() { return username + ":" password; }
}

And then injects as然后注入为

@Value("${secrets}")
List<Secret> secrets;

If you must use map.如果必须使用 map。 I think array of map are probably not what you desired.我认为 map 阵列可能不是您想要的。 Maybe you need one map which contains two keys, username1 and username2.也许您需要一个 map,其中包含两个密钥,用户名 1 和用户名 2。 The following might let you know how to obtain the map.下面可能会告诉您如何获取 map。

The yml file content is like that. yml文件内容就是这样。

secrets: "{username1:pw1,username2:pw1}"

The Java code field is like that. Java码域就是这样。

  @Value("#{${secrets}}")
  public Map<Integer,Integer> secrets;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM