Bean无法从其他软件包自动装配

问题描述 投票:0回答:1

我有一个配置类。在该配置类中,我正在创建RestTemplate类型的bean。此配置类位于'com.example.Config'。

我在'com.example.Controller'中的包中有一个Controller。

在我的主类(位于“ 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);
    }
}

我试图在控制器中自动连接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();
    }
}
java spring javabeans spring-bean
1个回答
0
投票

[如果可能,您可以将Main类移到com.example包中(从core包中移出)。在这种情况下,您可以使用@SpringBootApplication注释而无需指定要扫描的软件包。

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

也许会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.