【问题标题】:Read application variable (assoc array) form application.yml / java, spring从application.yml/java、spring中读取应用变量(assoc数组)
【发布时间】:2020-12-25 17:47:38
【问题描述】:

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

我已经将凭证写成这样的关联数组(我不知道有什么更好的方法):

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

然后我将这些值映射到带有@Value 注解的spring 应用程序:

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

   ...
}

但是 spring 不断抛出异常,因为它无法读取这些值。

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

【问题讨论】:

标签: java spring environment-variables yaml


【解决方案1】:

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

创建一个类帐户

class Account {
      private String login;
      private String password;

    //constructors, getters and setters here
}

并使用带有 @ConfigurationProperties 注释的类来阅读它

@Component
@ConfigurationProperties("app.mail")
class MyClass {
   private List<Account> accounts = new ArrayList<>();
   //getters and setters here
}

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

@Autowired
private MyClass myClass;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-22
    • 2019-02-11
    • 2019-01-22
    • 2013-08-02
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2019-05-23
    相关资源
    最近更新 更多