【问题标题】:Injecting several Spring Beans of the same class using application.properties使用 application.properties 注入同一类的多个 Spring Bean
【发布时间】:2017-11-17 14:22:51
【问题描述】:

我有一个由 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 文件中获取配置值)?

【问题讨论】:

  • 你在用spring boot吗?
  • 是的。我正在使用弹簧靴。

标签: java spring spring-boot


【解决方案1】:
@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;  

在任何弹簧组件中,您都会得到您想要的。 希望对你有帮助

【讨论】:

    【解决方案2】:

    试试这样的:

    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;
        }
    }
    

    24.6.1 Loading YAML

    我没有尝试过,但它应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-16
      • 2019-03-18
      • 2021-12-05
      • 2017-06-18
      • 1970-01-01
      • 2022-07-07
      相关资源
      最近更新 更多