簡體   English   中英

Bean 不會從不同的包自動裝配

[英]Bean not autowiring from a different package

我有一個配置類。 在那個配置類中,我創建了一個RestTemplate類型的 bean。 此配置類位於com.example.Config

我在位於com.example.Controller的包中有一個Controller

在我的Main類(位於com.example.Core )中,我有以下內容:

@SpringBootApplication(scanBasePackages = {"com.example.Config", "com.example.Controller"})
@EnableDiscoveryClient
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

我正在嘗試在我的Controller自動裝配RestTemplate bean,但是在啟動我的應用程序時,我收到以下錯誤:

Field `restTemplate` in `com.example.Controller.HelloWebClientController` required a bean of type `org.springframework.web.client.RestTemplate` that could not be found.
- User-defined bean method `restTemplate` in `RestConfig`

Action:

Consider revisiting the entries above or defining a bean of type `org.springframework.web.client.RestTemplate` in your configuration.

這是我的配置類:

@Configuration
public class RestConfig {

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

如果可能,您可以將Main類移動到com.example包(從core包)。 在這種情況下,您可以使用@SpringBootApplication注釋而不指定要掃描的包。

@SpringBootApplication
@EnableDiscoveryClient
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

也許它會有所幫助。

暫無
暫無

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

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