java - 为什么 spring 不能 Autowiring 简单类型?

标签 java spring dependency-injection autowired

在处理我们正在使用的特定案例时:

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

今天,我不得不在我的序列化器 bean 上 Autowiring 一个值,该值由 FactoryBean 提供。

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

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

最后在查看 bean 注入(inject)是如何工作的之后,我发现 Spring 从不注入(inject)“简单属性”

/**
 * 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文档中找到:

Please also note that it is not currently possible to autowire so-called simple properties such as primitives, Strings, and Classes (and arrays of such simple properties). (This is by-design and should be considered a feature.)

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

我只是想知道为什么在设计上禁止 Autowiring 简单属性,特别是在由 FactoryBean 注入(inject)的简单属性的情况下。

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

最佳答案

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

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

实际上我不是 100% 确定这会像上面那样工作,但你明白了,你可以尝试 #{myBean.someMethod()} 代替。

关于java - 为什么 spring 不能 Autowiring 简单类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9724490/

相关文章:

java - 无法通过java应用程序连接到数据库

java - 为什么在加载 webapp 时由 tomcat 容器在启动时自动创建监听器和过滤器实例?

java - 使用 Spring、Swing 和 SQLite 在 Java 中进行用户授权

java - Spring CrudRepository 将值插入 mysql 数据库

java - 使用 Spring 定义 bean

c# - 使用 FromAssembly 注册 CaSTLe Windsor 需要一些第 3 方引用的 dll,但不是全部

java - Spring注入(inject)、全局变量

java - 使用 log4j2 实现缓冲 IO 的方法

java - Spring MVC 忽略全局日期格式?

java - java swing中如何添加助记符?