簡體   English   中英

彈簧:@Autowired 沒有@Component

[英]Spring: @Autowired without @Component

在實際項目中,我發現以下代碼中可能會省略@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 版本的一個特性,如果該特性沒有記錄,它可能會在以后被刪除。

問題:使用@Autowired的類是否必須用@Component進行注釋(好吧,是一個bean)? 有沒有相關的官方文檔?

UPD伙計們,項目中沒有@Configuration和 XML 配置,我知道這樣的聲明從一個類中生成了一個 bean,但問題不在於它們。 我什至在上面的問題中寫了“(好吧,做個豆子)”來說明這一點。 @Autowired在非 bean 的類中工作嗎? 或者它可能聲明了將它用作 bean 的類?

有幾種方法可以在 Spring 中實例化 bean。
其中之一確實是使用@Component注釋,這樣,Spring 將掃描為組件掃描定義的所有包並初始化所有帶注釋的類(使用@Component或使用它的注釋之一 - 控制器、服務等。 )。

初始化 bean 的其他方法是使用配置類(用@Configuration注釋),其中包含用@Bean注釋的方法。 這些方法中的每一個都將創建一個 bean。

還有一個選項可以使用 xml 配置創建 bean,但這種方法越來越少,因為基於注釋的方法更方便

https://stackoverflow.com/a/3813725/755804 ,與autowireBean()可能從沒有被聲明為一個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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM