简体   繁体   English

在 Spring @Value('#{SPEL}) 中使用 Java 类

[英]Using Java classes inside Spring @Value('#{SPEL})

I would like to parse the property value into an custom Object.我想将属性值解析为自定义 Object。 Example;例子; i have application.properties;我有application.properties; say

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

And would like to convert that property into java LocalTime object.并且想将该属性转换为 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.我试过 web 和 stackoverflow,但没有得到具体的答案。 Please help.请帮忙。

Only workaround i know for this is constructor injection;我知道的唯一解决方法是构造函数注入; but this will bloat my constructor with many arguments但这会使我的构造函数膨胀很多 arguments

@Configuration
public class RuleUtils {

    public LocalTime weekDayMorningPeakStart;

    public RuleUtils(@Value("${rules.peakHours.weekday.morning.start}") String weekDayMorningPeakStart) {
         this.weekDayMorningPeakStart = LocalTime.parse(weekDayMorningPeakStart);
    }

You can use expression templating to parse into LocalTime, like show in docs您可以使用表达式模板来解析为 LocalTime,例如在文档中显示

@Value("#{ T(java.time.LocalTime).parse('${rules.peakHours.weekday.morning.start}')}")
private LocalTime localTime;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM