首页 > 解决方案 > Spring:没有@Component的@Autowired

问题描述

在一个真实的项目中,我发现@Component以下代码中可能会省略:

// no @Component !!!!!
public class MovieRecommender {

    private final CustomerPreference customerPreference;

    @Autowired
    public MovieRecommender(CustomerPreference customerPreference) {
        this.customerPreference = customerPreference;
    }

    // ...
}

@Component
public class CustomerPreference {...}

(示例取自 Spring 官方文档https://docs.spring.io/spring-framework/docs/4.3.x/spring-framework-reference/htmlsingle/#beans-autowired-annotation,文档显示没有@Component完全没有,这可能意味着它不是必需的,或者它只是没有显示。)

我工作的项目没有使用任何 XML bean 声明,但它使用了 Spring 以外的框架,因此有可能将类声明为 bean。或者它可能是我们使用的 Spring 版本的一个特性,如果没有记录该特性,它可能会在以后被删除。

问题: 使用的类必须用(嗯,是一个bean)@Autowired进行注释吗?@Component有没有这方面的官方文件?

UPD伙计们,@Configuration项目中没有也没有XML配置,我知道这样的声明从一个类中生成一个bean,但问题不在于它们。我什至在上面的问题中写了“(好吧,成为一个豆子)”来涵盖这一点。@Autowired在不是 bean 的类中工作吗?或者它可能声明了使用它作为 bean 的类?

标签: javaspringspring-boot

解决方案


根据https://stackoverflow.com/a/3813725/755804autowireBean()可以从未声明bean 的类中自动装配 bean。

@Autowired
private AutowireCapableBeanFactory beanFactory;

public void sayHello(){
    System.out.println("Hello World");
    Bar bar = new Bar();
    beanFactory.autowireBean(bar);
    bar.sayHello();
}

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;

public class Bar {
    @Autowired
    private Foo foo;

    public void sayHello(){
        System.out.println("Bar: Hello World! foo="+foo);
    }
}

另一方面,默认情况下,最新的 Spring 不假定使用的类@Autowire@Component-s。

UPD 至于提到的真实项目,堆栈跟踪显示构造函数是从createBean(). 也就是说,框架从框架配置中声明的类创建 bean。


推荐阅读