Spring:如何获取bean层次结构?

时间:2011-03-30 16:01:20

标签: java spring

是否可以获取注入bean的bean(通过Spring Framework)?如果是的话怎么样?

谢谢! 帕特里克

3 个答案:

答案 0 :(得分:0)

如果您正在寻找合作bean,可以尝试实施BeanFactoryAware

答案 1 :(得分:0)

只是为了扩展David的答案 - 一旦实现了BeanFactoryAware,就会得到BeanFactory的引用,您可以通过BeanFactory.ContainsBean(String beanName).

答案 2 :(得分:0)

这是一个BeanFactoryPostProcessor示例实现,可以帮助您:

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

当然,还有更多内容(如果你还要捕获原始bean的代理或其他)。 当然,上面的代码完全没有经过测试。

编辑: 要使用它,您需要在应用程序上下文中将其声明为bean。正如您已经注意到的,它需要将您的bean(您要监视的bean)注入其中(作为构造函数-arg)。

当你的问题提到“bean hiearchy”时,我编辑了在整个层次...IncludingAncestors中查找bean名称。此外,我假设你的bean是一个单独的,并且可以将它注入后处理器(虽然理论上postProcessor应该在其他bean之前初始化 - 需要查看它是否真的有效)。