【发布时间】: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