我正在做一个春季项目,需要从应用程序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}"
无需更改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] 删除。
我来说两句