簡體   English   中英

Spring:如何獲取bean層次結構?

[英]Spring: How to get the bean hierarchy?

是否有可能獲得注入bean的bean(通過Spring Framework)? 如果是的話怎么樣?

謝謝! 帕特里克

如果您正在尋找合作bean,您可以嘗試實現BeanFactoryAware

只是為了擴展David的答案 - 一旦實現了BeanFactoryAware,就會得到BeanFactory的引用,你可以通過BeanFactory.ContainsBean(String beanName)來查詢bean工廠中是否存在特定bean

這是一個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”時,我編輯了在整個層次中尋找bean的名字...IncludingAncestors祖先。 此外,我假設你的bean是一個單獨的,並且可以將它注入后處理器(雖然理論上postProcessor應該在其他bean之前初始化 - 需要查看它是否真的有用)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM