Can I dynamically create a list by scanning beans in the spring configuration file?

For example, I created many “test-my-service” objects in my Spring configuration, and each object has data related to a fake test case. Currently, I manually edit the Spring configuration every time I want to run a new script, or Script List. Is there a way to add a prefix to the bean name and then load all the beans with this prefix (or suffix) into a list or array? Sort of....

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

This is the code that I wrote in the letter. I could not get the beanFactory object initialized from the example 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); } } 
+3
source share
2 answers

You can use the ListableBeanFactory interface to get all the bean names and then load the ones that interest you:

 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, you can query them all by type rather than by name using ListableBeanFactory.getBeansOfType() or ListableBeanFactory.getBeanNamesForType() .

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

+14
source

I have never tried it before, but it looks like you can get a list of all the beans from the context: http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/beans/factory/ListableBeanFactory.html # getBeanDefinitionNames% 28% 29

It will not be difficult to filter out names and load matches from this.

+2
source

Source: https://habr.com/ru/post/950061/


All Articles