Spring boot 2 Converting Duration java 8 application.properties

后端 未结 5 1744
抹茶落季
抹茶落季 2021-02-20 08:48

I need to define Duration value (spring.redis.timeout) by application.properties.

I was trying to use one point defined in Spri

5条回答
  •  野的像风
    2021-02-20 09:03

    The Duration in the moment (Spring-Boot 2.0.4.RELEASE) it is not possible to use together with @Value notation, but it is possible to use with @ConfigurationProperties

    For Redis, you have RedisProperties and you can use the configuration:

    spring.redis.timeout=5s
    

    And:

    @SpringBootApplication
    public class DemoApplication {
    
      @Autowired
      RedisProperties redisProperties;
    
      public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
      }
    
      @PostConstruct
      void init() {
        System.out.println(redisProperties.getTimeout());
      }
    }
    

    It printed (parse as 5s):

    PT5S
    

    https://docs.oracle.com/javase/8/docs/api//java/time/Duration.html#parse-java.lang.CharSequence-

提交回复
热议问题