简体   繁体   English

我可以通过扫描spring配置文件中的bean来动态创建List吗?

[英]Can I dynamically create a List by scanning the beans in a spring configuration file?

For example, I have created a slew of 'test-my-service' Objects in my Spring config and each Object has data that concerns a contrived test scenario. 例如,我在Spring配置中创建了一系列'test-my-service'对象,每个Object都有关于人为测试场景的数据。 Currently I am manually editing the Spring config every time I want to run a new scenario, or a List of scenarios. 目前,每次我想运行新场景或场景列表时,我都会手动编辑Spring配置。 Is there a way I could add a prefix to a bean name, and then load all of the beans with that prefix (or suffix) into a List or Array? 有没有办法可以为bean名称添加前缀,然后将带有该前缀(或后缀)的所有bean加载到List或Array中? Something like.... 就像是....

<bean name="env1-test1"/>
<bean name="env2-test1"/>

This is the code that I ended up writing. 这是我最后编写的代码。 I wasn't able to get the beanFactory Object initialized from the example that I accepted earlier: 我无法从之前接受的示例中初始化beanFactory对象:

String[] beanNames = context.getBeanNamesForType(Inputs.class); 
for (String beanName : beanNames) { 
     if (beanName.startsWith("env")) { 
          System.out.println("Found a bean of type " + Inputs.class.getName()); 
          Inputs bean = (Inputs)context.getBean(beanName); 
          doTest(bean); 
     }
}

You can use the ListableBeanFactory interface to retrieve all bean names, and then load the ones you're interested in: 您可以使用ListableBeanFactory接口检索所有bean名称,然后加载您感兴趣的名称:

private @Autowired ListableBeanFactory beanFactory;

public void doStuff() {
   for (String beanName : beanFactory.getBeanDefinitionNames()) {
      if (beanName.startsWith("env")) { // or whatever check you want to do
         Object bean = beanFactory.getBean(beanName)
         // .. do something with it
      }
   }
}

Alternatively, if the target beans are all of the same type, then you can ask for them all by type, instead of by name, using ListableBeanFactory.getBeansOfType() or ListableBeanFactory.getBeanNamesForType() . 或者,如果目标bean都是相同的类型,那么您可以使用ListableBeanFactory.getBeansOfType()ListableBeanFactory.getBeanNamesForType()按类型而不是按名称请求它们。

The injected ListableBeanFactory will be the "current" application context. 注入的ListableBeanFactory将是“当前”应用程序上下文。

I've never tried before, but looks like you can get a list of all beans from the context: http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/beans/factory/ListableBeanFactory.html#getBeanDefinitionNames%28%29 我以前从未尝试过,但看起来你可以从上下文中获取所有bean的列表: http//static.springsource.org/spring/docs/2.0.x/api/org/springframework/beans/factory/ ListableBeanFactory.html#getBeanDefinitionNames%28%29

From that it wouldn't be hard to filter on the names and load the matches. 从那里过滤名称并加载匹配并不困难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM