我有一个配置类。在该配置类中,我创建了一个 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/