Java 自动连线实例使用构造函数为空

Java 自动连线实例使用构造函数为空,java,spring-boot,autowired,Java,Spring Boot,Autowired,Springboot新手我知道这已经被问了很多次了 我有下面的控制器,它有一个CustomRestTemplate自动连接。 CustomRestTemplate有另一个名为RestClientConfig的bean自动连接 RestClientConfig是否始终为空?我用@Component进行了注释,但它从未在CustomRestTemplate中初始化 @RestController @RequestMapping("/catalog") public class C

Springboot新手我知道这已经被问了很多次了

我有下面的控制器,它有一个CustomRestTemplate自动连接。 CustomRestTemplate有另一个名为RestClientConfig的bean自动连接

RestClientConfig是否始终为空?我用@Component进行了注释,但它从未在CustomRestTemplate中初始化

@RestController
@RequestMapping("/catalog")
public class CatalogController {

  @Autowired
  private CustomRestTemplate restTemplate;
.
.

CustomRestTemplate已自动连接RestClientConfig

在CustomRestTemplate中注入的RestClientConfig总是空的,为什么

@Component
public class CustomRestTemplate{

  @Autowired
  private RestClientConfig restClientConfig // always null;

  public CustomRestTemplate()
  {
    
  }
}

这是因为在创建Springbean时,
CustomRestTemplate
类中没有提供优先权的参数构造函数,所以有两种方法可以解决这个问题:删除构造函数和使用字段自动连接

@Component
public class CustomRestTemplate{

   @Autowired
   private RestClientConfig restClientConfig;


}
或者在构造函数中添加
RestClientConfig
作为参数,并使用构造函数自动连接

@Component
public class CustomRestTemplate{

  
  private RestClientConfig restClientConfig;

  @Autowired
  public CustomRestTemplate(RestClientConfig restClientConfig) {
    this.restClientConfig = restClientConfig;
    }
 }
@Component
public class CustomRestTemplate{

  
  private RestClientConfig restClientConfig;

  @Autowired
  public CustomRestTemplate(RestClientConfig restClientConfig) {
    this.restClientConfig = restClientConfig;
    }
 }