Spring:不带@Component的@Autowired

184*_*615 7 java spring spring-boot

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

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

    private final CustomerPreference customerPreference;

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

    // ...
}

@Component
public class CustomerPreference {...}
Run Code Online (Sandbox Code Playgroud)

(该示例取自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 的类?

Nir*_*evy 2

在 Spring 中实例化 bean 有多种方法。
其中之一确实是使用@Component注释,这样,Spring 将扫描为组件扫描定义的所有包并初始化所有带注释的类(使用@Component它的注释或使用它的注释之一 - 控制器、服务等)。

初始化 bean 的其他方法是使用配置类(用 注释@Configuration),其中包含用 注释的方法@Bean。这些方法中的每一个都会创建一个 bean。

还有一个选项是使用 xml 配置创建 bean,但这变得越来越不常见,因为基于注释的方法更方便