代码之家  ›  专栏  ›  技术社区  ›  Mr.H.

Spring-SpEL访问配置Bean

  •  0
  • Mr.H.  · 技术社区  · 6 年前

    我在一个遗留软件中工作,其中大部分配置都是从外部化的 application.properties 它驻留在一个名为 custom.properties 它将被读入这样声明的配置bean中。

    @Configuration
    @ConfigurationProperties(locations = "classpath:custom.properties", ignoreUnknownFields = true, prefix = "custom")
    public class CustomProperties {
    ...
    }
    

    此应用程序有一些计划任务,这些任务被声明为以固定的时间间隔工作。 @Scheduled(cron = "0 0 16 * * 3") 直到现在一切都很好。最近我被要求在一个可配置的时间内完成这项工作。所以我给它添加了另一个属性 和一个属性 CustomProperties (包括getter和setter)。接下来,我修改了预定的注释,使其看起来像这样。 @Scheduled(cron = "${@customProperties.cronJob1Schedule}")

    启动应用程序时,出现以下异常:

    java.lang.IllegalStateException: Encountered invalid @Scheduled method 'cronJob1': Could not resolve placeholder '@customProperties.cronJob1Schedule' in string value "${@bwvProperties.cronJob1Schedule}"
        at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.processScheduled(ScheduledAnnotationBeanPostProcessor.java:406)
        at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.postProcessAfterInitialization(ScheduledAnnotationBeanPostProcessor.java:282)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:422)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
    

    2 回复  |  直到 6 年前
        1
  •  4
  •   Pavel Horal    6 年前

    请注意,在Spring处理的字符串值上有两种不同的机制:

    属性解析- ${my.property}

    Spring能够替换占位符 ${placeholder} 配置的值 property sources converter 如果需要)。

    #{spel.expression}

    Spring能够运行 #{} 通过 SPeL 解释者。这提供了更强大的工具,因为您可以从表达式内部与应用程序代码交互,例如通过从bean中获取属性 #{@cumstomProperties.cronJob1Schedule}

    太长,读不下去了

    你只需要换一下 ${ 对于 #{ 在注释值中。

        2
  •  1
  •   Robin-Hoodie    6 年前

    我相信您输入了一个错误,假设您正在注入与以下类似的配置属性:

    @Autowired private CustomProperties bwvProperties

    应该是的 #{bwvProperties.cronJob1Schedule} -放下枪 @ ,更改 $ #