java - Bean 不从不同的包 Autowiring

标签 java spring javabeans spring-bean

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

我的包中有一个 Controller,位于 com.example.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 中 Autowiring 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);
    }
}

也许会有帮助。

关于java - Bean 不从不同的包 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60901259/

相关文章:

android - 如何从另一个类中访问 Bean 的存储值

java - 将动态属性映射读入 Spring 托管 bean

validation - 如何将 jersey 与 guice 和 bean 验证集成

java - 如何用Maven依赖系统包?

java - 错误: Unable to access jarfile when I launch a process builder command

spring - 如何使用 OAuth2RestTemplate?

Android和IOS后端框架选择?

java - for 循环内的 if else 语句[java]

java - NotificationListenerService.cancelNotification 抛出 NullPointerException

java - 在 Spring Web Flux 中捕获异常