0

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("${app.mail.accounts}")
  private List<Map<String, String>> 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 'intelaw.mail.accounts' in value "${app.mail.accounts}"
Maik
  • 310
  • 1
  • 11
whatspoppin
  • 353
  • 4
  • 14

1 Answers1

2

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("app.mail")
class MyClass {
   private List<Account> accounts = new ArrayList<>();
   //getters and setters here
}

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

@Autowired
private MyClass myClass;

void someMethod() {
  myClass.getAccounts();
}
Mario Codes
  • 689
  • 8
  • 15
Jerin D Joy
  • 750
  • 6
  • 11