3

I would like to parse the property value into an custom Object. Example; i have application.properties; say

rules.peakHours.weekday.morning.start=10:15:45

And would like to convert that property into java LocalTime object.

@Configuration
public class RuleUtils {


    @Value("#{localTime.parse(\"${rules.peakHours.weekday.morning.start}\")}")
    public LocalTime weekDayMorningPeakStart;

I have tried the below, but not helping.

    @Bean
    @ConfigurationProperties("localTime")
//    @EnableConfigurationProperties(LocalTime.class)
    public Class<LocalTime> getLocalTime() {

        return LocalTime.class;
    }

Getting below error:

 EL1008E: Property or field 'localTime' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'

I tried web and stackoverflow, but not getting specific answer. Please help.

Only workaround i know for this is constructor injection; but this will bloat my constructor with many arguments

@Configuration
public class RuleUtils {

    public LocalTime weekDayMorningPeakStart;

    public RuleUtils(@Value("${rules.peakHours.weekday.morning.start}") String weekDayMorningPeakStart) {
         this.weekDayMorningPeakStart = LocalTime.parse(weekDayMorningPeakStart);
    }
Kanagavelu Sugumar
  • 18,766
  • 20
  • 94
  • 101

1 Answers1

5

You can use expression templating to parse into LocalTime, like show in the Expression templating section

@Value("#{ T(java.time.LocalTime).parse('${rules.peakHours.weekday.morning.start}')}")
private LocalTime localTime;
Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98