从Spring读取application.yml / java形式的应用程序变量(关联数组)

whatspoppin:

我正在做一个春季项目,需要从应用程序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会继续抛出Exception,因为它无法读取这些值。

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

无需更改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();
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用变量名从 Java Spring 中的 application.yml 读取值?

无法从Java Spring Boot项目中的application.yml文件读取用户定义的类的列表

如何从Java中的application.yml文件读取

jhipster应用程序中application-prod.yml和application-dev.yml之间的区别

Spring-从@Entity类中的application.yml读取值

执行应用程序时未使用application.yml中的spring.cloud.config设置

使用apache-cxf在spring boot 2应用程序中未加载application.yml

在Rails应用程序中优化application.yml文件

Gitlab秘密变量>>> Spring Boot application.yml

Spring Boot application.yml中的环境变量

Spring应用程序的库模块如何向应用程序的application.yml中添加其他配置?

Spring-YML数组属性为null

将YML文件中的数组注入Spring

从xml配置读取spring yml属性

Spring Boot yml 文件读取顺序

Spring Boot 2.4.2外部application.yml无法在Docker容器中读取

Spring Boot-无法从application.yml中读取自定义属性

无法在 Spring Boot 中使用 @Value 从 application.yml 读取属性

得到的NullPointerException让应用程序名称Springboot application.yml时

Spring Boot-每个开发人员的应用程序yml

谁将Spring Scheduled Job Cron添加到应用程序yml文件中?

Spring中的Maven配置文件和应用程序yml文件

应用程序yml属性的Spring SpEL表达式评估

如何在Spring Boot应用程序中使用配置(properties / yml)文件中的属性?

为什么Spring Boot在打包时不加载应用程序yml(带有gradle)?

如何在Spring Boot中为应用程序yml定义复杂列表?

如何在 application.yml 中设置环境变量 - Spring Boot

Resilience4j Retry + Spring Boot 2 application.yml配置未应用

从bash读取yml文件并将其存储到变量中