Spring: How to get a bean hierarchy?

Is it possible to get beans into which a bean has been introduced (via Spring Framework)? And if so, how?

Thanks! Patrick

+4
source share
3 answers

Here is an example implementation of BeanFactoryPostProcessor that can help you:

 class CollaboratorsFinder implements BeanFactoryPostProcessor { private final Object bean; private final Set<String> collaborators = new HashSet<String>(); CollaboratorsFinder(Object bean) { if (bean == null) { throw new IllegalArgumentException("Must pass a non-null bean"); } this.bean = bean; } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { for (String beanName : BeanFactoryUtils.beanNamesIncludingAncestors(beanFactory)) { BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); if (beanDefinition.isAbstract()) { continue; // assuming you're not interested in abstract beans } // if you know that your bean will only be injected via some setMyBean setter: MutablePropertyValues values = beanDefinition.getPropertyValues(); PropertyValue myBeanValue = values.getPropertyValue("myBean"); if (myBeanValue == null) { continue; } if (bean == myBeanValue.getValue()) { collaborators.add(beanName); } // if you're not sure the same property name will be used, you need to // iterate through the .getPropertyValues and look for the one you're // interested in. // you can also check the constructor arguments passed: ConstructorArgumentValues constructorArgs = beanDefinition.getConstructorArgumentValues(); // ... check what has been passed here } } public Set<String> getCollaborators() { return collaborators; } } 

Of course, there is much more (if you also want to catch the proxies of your original bean or something else). And of course, the above code has not been fully tested.

EDIT: To use this, you need to declare it as a bean in the context of your application. As you already noticed, this requires your bean (the one you want to control) (as the arg constructor).

As your question relates to "bean hiearchy", I edited to search for bean names throughout the hierarchy ...IncludingAncestors . In addition, I assumed that your bean is singleton and that it can be embedded in a postprocessor (although theoretically postProcessor should be initialized before the other beans should see if this really works).

0
source

If you are looking for collaboration beans, you can try BeanFactoryAware

0
source

Just to extend David's answer. After you have implemented BeanFactoryAware, you will get a link to BeanFactory , which you can use to query mainly for a bean member in a bean factory via BeanFactory.ContainsBean (String beanName).

0
source

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


All Articles