Search code examples
javaspringspring-bootredis

Changing a type of param in application.yml


I have spring application and trying to cache data with Redis. For this cache i am trying to set TTL to 10 minutes and for some reason i can not use long type, only format like 'PT10M'.

My application.yml looks like this:

cache:
    service-available-event:
        ttl: PT10M

Config class:

import org.springframework.cache.CacheManager;

@Configuration
@EnableCaching
public class RedisConfiguration {

    @Bean
    @ConfigurationProperties("cache.service-available-event")
    public CustomCacheConfig serviceAvailableEventCacheConfig() {
        return new CustomCacheConfig();
    }

    public class CustomCacheConfig extends CacheConfig {

        public void setTTL(Duration ttl) {
            super.setTTL(ttl.toMillis());
        }
    }
}

Error:

Description:

Failed to bind properties under 'cache.service-available-event.t-t-l' to long:

    Property: cache.service-available-event.t-t-l
    Value: "PT10M"
    Origin: class path resource [application.yml] - 62:14
    Reason: failed to convert java.lang.String to long (caused by java.lang.NumberFormatException: For input string: "PT10M")

Action:

Update your application's configuration

Is there a way to change format from long to string for application.yml ?


Solution

  • No, you can't change the type in the application.yml.

    You can either change the value you provide, so it can be interpreted/parsed into a long, or you can change your code to accept a String when it reads the property you defined.

    Spring can auto-assign fields with values from the application.yml file like this:

        @Value("${your.property.key.}")
        private String propertyName;
    

    In this way, you can set the type you want to interpret from the application.yml.