英文:
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("${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}"
答案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("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();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论