2

New to Springboot I know this has been asked so many times....

I have the following controller which has a CustomRestTemplate autowired. CustomRestTemplate has another bean autowired called RestClientConfig .

RestClientConfig is always null? I annotated with @Component but it never gets initialized inside CustomRestTemplate

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

  @Autowired
  private CustomRestTemplate restTemplate;
.
.

CustomRestTemplate has RestClientConfig autowired

RestClientConfig injected inside CustomRestTemplate is always null, why is that?

@Component
public class CustomRestTemplate{

  @Autowired
  private RestClientConfig restClientConfig // always null;

  public CustomRestTemplate()
  {
    
  }
}
@Component
public class RestClientConfig {

  private String val;

  public RestClientConfig()
  {
    this.val = "test";
  }
}
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
user955165
  • 447
  • 3
  • 8
  • 17

1 Answers1

1

It is because of the no-arg constructor provided in CustomRestTemplate class which takes precedence while creating spring bean, there are two ways to fix this remove the constructor and Autowire using field

@Component
public class CustomRestTemplate{

   @Autowired
   private RestClientConfig restClientConfig;


}

Or add RestClientConfig as an argument in the constructor and use constructor autowiring

@Component
public class CustomRestTemplate{

  
  private RestClientConfig restClientConfig;

  @Autowired
  public CustomRestTemplate(RestClientConfig restClientConfig) {
    this.restClientConfig = restClientConfig;
    }
 }
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98