为什么不能弹簧自动装配简单类型?

时间:2012-03-15 16:57:17

标签: java spring dependency-injection autowired

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

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

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

我的第一次尝试只是使用简单的factorybean id,但它不起作用。

之后我尝试使用@Resource@Autowired@Qualifier等在此处阅读的许多解决方案......

最后看了豆注射是如何工作的,我发现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注入简单属性的情况下。

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

2 个答案:

答案 0 :(得分:2)

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

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

实际上,我并非100%确定这会完全如上所述,但您明白了,您可以尝试使用#{myBean.someMethod()}

答案 1 :(得分:0)

好吧,考虑一下上下文中有多个相同(原始)类型的“bean”的情况。春天怎么可能想出哪一个要注射?

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

我猜测Spring开发人员刚刚决定在该功能中遇到更多麻烦而不是好处,因为它几乎总是无法工作。