【问题标题】:Why can't spring autowire simple types?为什么不能弹簧自动装配简单类型?
【发布时间】:2012-03-15 16:57:16
【问题描述】:

在我们正在使用的特定案例中工作:

context.getAutowireCapableBeanFactory().autowireBeanProperties(
   serializer, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false
);

今天我必须在我的序列化程序 bean 上自动装配一个值,该值由 FactoryBean 提供。

我的第一次尝试只是使用简单的 factorybean id,但没有成功。

在那之后,我尝试了许多我在这里阅读的解决方案,使用@Resource@Autowired@Qualifier 等...

最后在查看了 bean 注入的工作原理后,我发现 Spring 从来没有注入“简单属性”

/**
 * Return an array of non-simple bean properties that are unsatisfied.
 * These are probably unsatisfied references to other beans in the
 * factory. Does not include simple properties like primitives or Strings.
 * @param mbd the merged bean definition the bean was created with
 * @param bw the BeanWrapper the bean was created with
 * @return an array of bean property names
 * @see org.springframework.beans.BeanUtils#isSimpleProperty
 */
protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
    Set<String> result = new TreeSet<String>();
    PropertyValues pvs = mbd.getPropertyValues();
    PropertyDescriptor[] pds = bw.getPropertyDescriptors();
    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) &&
                !BeanUtils.isSimpleProperty(pd.getPropertyType())) {
            result.add(pd.getName());
        }
    }
    return StringUtils.toStringArray(result);
}

我还在 Spring 文档中找到:

另请注意,目前无法自动接线 所谓的简单属性,例如原语、字符串和类 (以及这些简单属性的数组)。 (这是设计使然,应该 被认为是一个特征。)

我终于知道为什么我的工厂 bean 不能注入我的属性:要注入的 bean 是一个 Enum,它是一个“简单属性”(根据代码)

我只是想知道为什么在设计上禁止自动装配简单属性,尤其是在FactoryBean 注入的简单属性的情况下。

另外,我看到按类型自动装配字符串可能是个问题,但是按名称自动装配它,这是怎么回事?

【问题讨论】:

    标签: java spring dependency-injection autowired


    【解决方案1】:

    你应该能够用springEL实现你所需要的:

    class MyClass {
      @Value("#{factoryBeanName}")
      private int myValue;
      ...
    }
    

    实际上,我不是 100% 确定这会完全按照上面的方式工作,但你明白了,你可以试试 #{myBean.someMethod()}

    【讨论】:

      【解决方案2】:

      好吧,考虑一下上下文中有多个相同(原始)类型的“bean”的情况。 Spring 怎么可能确定注入哪一个?

      这与 Spring 自动装配任何东西的情况基本相同,但在 Spring 上下文中更有可能存在多个 String 或 Integer 实例,然后是 com.yourcorp.SomeClass 的实例。事实上,如果您在 spring 上下文中枚举 bean,您会发现其中几乎总是有多个 String 实例。

      我猜 Spring 开发人员只是认为该功能弊大于利,因为它几乎总是不起作用。

      【讨论】:

      • 检查我问题的最后一行。按名称自动装配应该能够工作,因为简单类型的 xml 装配按名称工作......
      猜你喜欢
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-08
      • 2016-09-27
      相关资源
      最近更新 更多