2011-03-30 136 views
4

是否有可能獲得注入bean的bean(通過Spring框架)?如果是的話,怎麼樣?Spring:如何獲取bean層次結構?

謝謝! 帕特里克

+0

你的意思是,如果'A'被注入'B'和'C',那麼你想問'API'爲'B'和'C',給定'A'? – skaffman 2011-03-31 09:43:33

+0

你能否改進這個問題?是否有可能讓你的bean註冊爲「匿名」bean?你的豆可以由FactoryBean生產嗎?如果在2個或更多 appContexts/beanFactories之間建立了一個層次結構,那麼也要考慮到您的bean可能被注入到子appContexts/beanFactories中。 另外,正如Costi已經提到的,可能會出現這樣的情況,即您的bean被代理。 – 2011-03-31 11:39:15

回答

0

在這裏,豆工廠particualr豆是一個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)被注入它(作爲構造器參數)。

由於您的問題涉及到「bean hiearchy」,我編輯了整個層次...IncludingAncestors以查找bean名稱。另外,我認爲你的bean是一個單例,並且可以將它注入後處理器(雖然理論上postProcessor應該在其他bean之前初始化 - 需要看看它是否實際工作)。