Home > Enterprise >  how to use constructor autowried
how to use constructor autowried

Time:01-16

I can get it working using field autowired.

@Component
public class ZMyServiceConstructor {

   @Autowired
   private RestTemplate restTemplate;

    @Value("${my_test_property}")
    private String url;

}

I'd like to use constructor autowried. When I don't add any construtor, or I use either @NoArgsConstructor or @RequiredArgsConstructor, url has value. But restTemplate is null

@Component
//@NoArgsConstructor 
//@RequiredArgsConstructor
public class ZMyServiceConstructor {

   private RestTemplate restTemplate;

    @Value("${my_test_property}")
    private String url;

}

If I use @AllArgsConstructor, it gives me error:

required a bean of type 'java.lang.String' that could not be found

How to get this working?

Updated:

  1. Adding final to field restTemplate for lombok to build a constructor

  2. @Value can't be used in final field. The field will be injected after constructor is called. @Value annotation not working in constructor

    @Component
     @RequiredArgsConstructor
     public class ZMyServiceConstructor {
    
        private final RestTemplate restTemplate;
    
        @Value("${my_test_property}")
        private String url;
    
     }
    

This equals to below

@Component
public class ZMyServiceConstructor {

    private final RestTemplate restTemplate;

    @Value("${my_test_property}")
    private String url;

    @Autowired
    public ZMyServiceConstructor(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
}

CodePudding user response:

I see two problems here

First:

You're trying to use RestTemplate without building one Try to build your restTemplate like this:

@Configuration
public class RestTemplateConfiguration {
    @Bean
    public RestTemplate restTemplateBuilder() {
        return new RestTemplateBuilder().build();
    }
}

Second:

You're using Lombok's constructors wrong. Try this:

@Component
@RequiredArgsConstructor
public class ZMyServiceConstructor {
    private final RestTemplate restTemplate;

    @Value("${my_test_property}")
    private final String url;
}

CodePudding user response:

Try creating a @Configuration class where you define your RestTemplate bean. https://www.digitalocean.com/community/tutorials/spring-resttemplate-example.

Also you should use @RequiredArgsConstructor and use private final RestTemplate restTemplate. It seems like your problem with @AllArgsConstructor is that spring boot is trying to inject your String attribute with a bean that (for obvious reasons) can´t be found.

  • Related