我有一个由Spring驱动的安全测试。我想创建一组测试用户(currentUser,anotherUser,adminUser等)。用户的凭据将存储在application.properties中,如下所示:
test.currentUser.username=user1
test.currentUser.password=secret
test.adminUser.username=admin
test.adminUser.password=admin_password
...
有一个类可以为用户构造一个对象。它看起来像这样:
@Component
public class UserObject{
public UserObject(
@Value("${test.currentUser.username}") String username,
@Value("${test.currentUser.password}") String password){
//Use username and password to do some authentication stuff
}
}
客户端测试类看起来像这样:
public class TestClass{
@Autowired
public TestClass(UserObject userObject){
}
}
如何更改上面的类,以便Spring以某种方式注入几个UserObject(并从application.properties文件中获取配置值)?
答案 0 :(得分:0)
@ConfigurationProperties
@Getter
@Setter
@Configuration
public class Test {
Map<String, String> credentials;
}
@Configuration
public class TestCreate {
@Bean(name = "userList")
public List<UserObject> creteUser(Test test) {
List<UserObject> users = new ArrayList<>();
test.getCredentials().entrySet().forEach(entry -> {
UserObject user = new UserObject( entry.getKey(), entry.getValue());
users.add(user);
});
return users;
}
}
application.properties
credentials.user1=secret //user1 is key, secret is value
credentials.user2=someothersecret
现在,如果你这样做
@Autowired
List<UserObject> userList;
在任何一个弹簧组件中,你得到你想要的。 希望它有所帮助
答案 1 :(得分:0)
尝试这样的事情:
test:
users:
- user1,secret1
- user2,secret2
将转化为这些属性:
test.users[0]={user1, secret1}
test.users[1]={user2, secret2}
@ConfigurationProperties(prefix="test")
public class Config {
private List<String[]> users= new ArrayList<String[]>();
public List<String[]> getUsers() {
return this.servers;
}
}
我没有尝试过,但它应该有效。