tags:

views:

36

answers:

2

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. Currently I am manually editing the Spring config every time I want to run a new scenario, or a List of scenarios. 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? 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:

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); 
     }
}
A: 

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

From that it wouldn't be hard to filter on the names and load the matches.

Rodney Gitzel
+3  A: 

You can use the ListableBeanFactory interface to retrieve all bean names, and then load the ones you're interested in:

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().

The injected ListableBeanFactory will be the "current" application context.

skaffman