读取应用程序变量(关联数组)来自 application.yml / java,spring

huangapple go评论74阅读模式
英文:

Read application variable (assoc array) form application.yml / java, spring

问题

我正在进行一个Spring项目,在这个项目中,我需要从应用程序yml文件中读取多个帐户凭据(登录和密码)。

我已经将这些凭据写成了一个关联数组,就像这样(我不知道有更好的方法来做这个):

app:
  mail:
    accounts:
    - login: firstlogin
      password: firstpassword
    - login: secondlogin
      password: secondpassword

然后,我使用@Value注解将这些值映射到Spring应用程序中:

@Service
public class MyClass {
 
  @Value("${app.mail.accounts}")
  private List<Map<String, String>> accounts;

   ...
}

但是Spring一直抛出异常,因为它无法读取这些值。

注入自动装配的依赖项失败;嵌套异常是java.lang.IllegalArgumentException:
无法解析占位符'intelaw.mail.accounts'中的值"${app.mail.accounts}"
英文:

I am working on a spring project where I need to read multiple account credentials (login and password) from application yml file.

I have written the credentials as an associative array like this (I don't know any better way to do it):

app:
  mail:
    accounts:
    - login: firstlogin
      password: firstpassword
    - login: secondlogin
      password: secondpassword

Then I mapped these values to spring application with @Value annotation:

@Service
public class MyClass {
 
  @Values(&quot;${app.mail.accounts}&quot;)
  private List&lt;Map&lt;String, String&gt;&gt; accounts;

   ...
}

But spring keep throwing an Exception because it fails to read these values.

Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException:
Could not resolve placeholder &#39;intelaw.mail.accounts&#39; in value &quot;${app.mail.accounts}&quot;

答案1

得分: 2

不更改您的application.yml,您可以调整您的数据结构使其正常工作。

创建一个类 Account

class Account {
      private String login;
      private String password;

    // 构造函数,getter和setter在这里
}

并且使用带有 @ConfigurationProperties 注解的类进行读取

@Component
@ConfigurationProperties("app.mail")
class MyClass {
   private List<Account> accounts = new ArrayList<>();
   // 这里是getter和setter
}

在您的服务类中,您可以这样使用:

@Autowired
private MyClass myClass;

void someMethod() {
  myClass.getAccounts();
}
英文:

Without changing your application.yml, you can tune your datastructures and make this work.

Create a class Account

class Account {
      private String login;
      private String password;

    //constructors, getters and setters here
}

and read it using a class annotated with @ConfigurationProperties

@Component
@ConfigurationProperties(&quot;app.mail&quot;)
class MyClass {
   private List&lt;Account&gt; accounts = new ArrayList&lt;&gt;();
   //getters and setters here
}

and in your service class, you can use it like :

@Autowired
private MyClass myClass;

void someMethod() {
  myClass.getAccounts();
}

huangapple
  • 本文由 发表于 2020年9月7日 17:57:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63775304.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定