无法在@Scheduled批注中使用@ConfigurationProperties

Pet*_*edy 6 spring spring-boot

我正在使用@ConfigurationProperties来定义属性my.delay

@ConfigurationProperties( "my" )
public class MyProperties {

    private long delay = 1000L;

    public long getDelay() {
        return delay;
    }
    public void setDelay(long delay) {
        this.delay = delay;
    }
}
Run Code Online (Sandbox Code Playgroud)

在调度程序方法中,我尝试使用my.delay

@SpringBootApplication
@EnableScheduling
@EnableConfigurationProperties( { MyProperties.class } )
public class TestSprPropApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestSprPropApplication.class, args);
    }

    @Scheduled( fixedDelayString = "${my.delay}" )
    public void schedule() {
        System.out.println( "scheduled" );
    }
}
Run Code Online (Sandbox Code Playgroud)

然后出现以下错误:

Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method 'schedule': Could not resolve placeholder 'my.delay' in string value "${my.delay}"
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.processScheduled(ScheduledAnnotationBeanPostProcessor.java:454) ~[spring-context-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.postProcessAfterInitialization(ScheduledAnnotationBeanPostProcessor.java:324) ~[spring-context-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:423) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1633) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
Run Code Online (Sandbox Code Playgroud)

Ada*_*lik 5

您可以使用 SpEL 表达式来解决该问题,该表达式使用引用 bean@beanName

你会这样使用它:

@Scheduled(fixedDelayString = "#{@myProperties.delay}")
Run Code Online (Sandbox Code Playgroud)

请注意,#{}使用的是(SpEL 表达式)而不是${}(属性占位符)。


Pat*_*ick 2

我不确定您的方法是否有解决方案。但是为了简化你的代码并且还有一个默认值,你可以这样做:

不需要有MyProperty根本您可以将其删除。

@Scheduled使用此默认值更新您的注释:

 @Scheduled( fixedDelayString = "${my.delay:1000}" )
Run Code Online (Sandbox Code Playgroud)

这意味着如果 Spring 找不到某个属性,my.delay它将使用:. 在你的情况下是1000.

如果您想覆盖默认值,只需在application.properties文件中添加该属性:

my.delay=5000
Run Code Online (Sandbox Code Playgroud)