一尘不染

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

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;
    }
}

在调度程序方法中,我尝试使用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" );
    }
}

然后出现以下错误:

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]

阅读 689

收藏
2020-05-30

共1个答案

一尘不染

我不确定是否有适合您的方法的解决方案。但是为了简化代码并具有默认值,您可以这样:

完全不需要MyProperty文件。您可以删除它。

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

 @Scheduled( fixedDelayString = "${my.delay:1000}" )

这意味着,如果Spring找不到my.delay它的属性,则在之后使用默认值:。就您而言1000

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

my.delay=5000
2020-05-30