0

我正在尝试编写一个 Spring BeanFactoryPostProcessor,它可以找到任何定义了 init 方法的 bean。我很幸运地找到了具有名称的 bean,但没有像以下示例中的目标 bean 那样嵌套无名 bean:

<bean id="aclDao" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="transactionManager"><ref bean="transactionManager"/></property>
    <property name="target">
        <bean class="com.vidsys.dao.impl.acl.ACLDaoImpl" init-method="init">
            <property name="sessionFactory"><ref local="sessionFactory"/></property>
        </bean>
    </property>
    <property name="transactionAttributes">
    <props>
    <prop key="*">PROPAGATION_REQUIRED</prop>
    </props>
  </property>
</bean>

当我在 BeanFactoryPostProcessor 中列出 bean 时,我似乎只得到了名称如下代码的bean:

public class BeanInitializationFinder implements BeanFactoryPostProcessor, Ordered {
  @Override
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
    throws BeansException {

      //String[] beanDefs = BeanFactoryUtils.beanNamesIncludingAncestors(beanFactory);
      String[] beanDefs = beanFactory.getBeanDefinitionNames();
      for(String defName : beanDefs) {
          BeanDefinition def = beanFactory.getBeanDefinition(defName);
          if(null == def.getBeanClassName() || !(def instanceof AbstractBeanDefinition)) 
              return;
          }
          AbstractBeanDefinition abd = (AbstractBeanDefinition) def;
          try {
              if(abd.getFactoryMethodName() == null && abd.getFactoryBeanName() == null) 
                  Class<?> beanClass = Class.forName(abd.getBeanClassName()); 
                  if(InitializingBean.class.isAssignableFrom(beanClass) || null != abd.getInitMethodName()) {
                        beansWithInits.add(defName);
                  }
              }
          }
          catch(Exception e) {
              throw new BeanIntrospectionException("Failed to instrospect bean defs", e);
          }
      }
  }

}

我想获取所有具有 init 方法的 bean,包括无名的嵌套 bean。我可以这样做吗?

4

1 回答 1

1

您可以检索嵌套的 BeanDefinition,但不能通过beanFactory.getBeanDefinition. 获得嵌套 bean 定义的唯一方法是通过PropertyValues父级BeanDefinition- 您需要遍历图表。

例如(并且缺少任何空值检查):

BeanDefinition parentDef = beanFactory.getBeanDefinition(defName);
for (PropertyValue property : parentDef.getPropertyValues().getPropertyValues()) {
    Object value = property.getValue();
    if (value instanceof BeanDefinitionHolder) {
        BeanDefinition nestedDef = ((BeanDefinitionHolder)value).getBeanDefinition();
    }
}

鉴于图遍历与访问者模式配合得很好,您可以子类化org.springframework.beans.factory.config.BeanDefinitionVisitor以更简洁的方式执行此操作。

于 2012-07-04T10:00:22.640 回答