2011-03-30 109 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之前初始化 - 需要看看它是否实际工作)。