Home > Software engineering >  Using @Value in spring beans at initialization
Using @Value in spring beans at initialization

Time:02-03

I need to provide timeouts from application.properties file, but at initialization it fails because properties are not yet loaded. What is best practice to get them loaded?

@Configuration
@AllArgsConstructor
@Slf4j
public class Config {

    @Value("${connectionTimeout}") 
    int connectionTimeout;
    @Value("${responseTimeout}") 
    int responseTimeout;

    @Bean
    public ClientHttpConnector getConnector() {
        HttpClient client = HttpClient.create();

        client.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectionTimeout)
                .responseTimeout(Duration.ofMillis(responseTimeout));

        return new ReactorClientHttpConnector(client);

    }
    @Bean
    public WebClient webClient() {
        return WebClient.builder().defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                .clientConnector(getConnector())
                .build();
    }

application.properties from resource folder

connectionTimeout=30000
responseTimeout=30000

As suggested in other similar posts I tried using @ConfigurationProperties, but that didn't work at all. Is there some easier way to get them loaded that I am not aware of?

CodePudding user response:

Try injecting the values via constructor:

public Config(@Value("${connectionTimeout}") int connectionTimeout,
              @Value("${responseTimeout}") int responseTimeout) {
    // assign to fields
}

CodePudding user response:

Try using Environment class.

@Configuration
public class Config {

   private final Environment environment;

   @Autowired
   public Config(Environment environment) {
       this.environment = environment;
   }

   @Bean
   public SimpleBean simpleBean() {
       SimpleBean simpleBean = new SimpleBean();
       simpleBean.setConfOne(environment.getProperty("conf.one"));
       simpleBean.setConfTwo(environment.getProperty("conf.two"));
       return simpleBean;
   } 
}

CodePudding user response:

The error you got

org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'getConnector' defined in ...config.Config: 
Unsatisfied dependency expressed through method 'getConnector' parameter 0;
nested exception is org.springframework.beans.TypeMismatchException:
 Failed to convert value of type 'java.lang.String' to required type 'int';
 nested exception is java.lang.NumberFormatException: For input string: 
"${connectionTimeout}"  <----- 

says that it tries to read "${connectionTimeout}" as a value. As if you had

connectionTimeout=${connectionTimeout} 

in your application.properties

My intuition is that the problem comes from

    @Value("${connectionTimeout}") 
    int connectionTimeout;
    @Value("${responseTimeout}") 
    int responseTimeout;

Hope it helps you debugg

  • Related