Spring SpEL访问配置bean

时间:2018-09-05 07:39:53

标签: spring spring-el

我正在使用旧版软件,其中大多数配置是从application.properties外部化的,它驻留在名为custom.properties的文件中,该文件将被读入这样声明的配置bean中。

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

此应用程序具有一些计划的任务,这些任务被声明为以固定的时间间隔和时间工作。 @Scheduled(cron = "0 0 16 * * 3")到目前为止,一切正常。最近,有人要求我在可配置的时间进行此cronjob。因此,我在custom.properties中添加了另一个属性,并在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)

以前有人遇到过这个问题吗?为什么我不能在SpEL中访问配置bean?

2 个答案:

答案 0 :(得分:3)

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

属性解析-def lookup(self, var=var): var = var

Spring可以用配置的property sources中的值替换占位符${my.property}。此过程仅用字符串值替换字符串键(并在需要时通过converter运行它)。

Spring Expression Language评估-${placeholder}

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

TL; DR

您只需要在注释值中将#{@cumstomProperties.cronJob1Schedule}切换为${

答案 1 :(得分:0)

假设您要注入与此类似的配置属性,我相信您已经犯了错字

@Autowired private CustomProperties bwvProperties

应该为#{bwvProperties.cronJob1Schedule}-放下@,将$更改为#

相关问题