2017-02-15 143 views
3

我正在使用@ConfigurationProperties来定义属性my.delay无法在@Scheduled注释中使用@ConfigurationProperties

@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] 
+0

你可以显示你的'application.properties'文件。您也可以将该属性直接注入到计划的注释中。 – Patrick

+0

@Patrick我的'application.properties'是空的。它应该使用MyProperties中指定的值,并且只有在application.properties中设置了my.delay时才会覆盖它。至少这是我的意图。 –

+0

在属性文件中创建'my.delay = 1000',它应该可以工作。不确定这是另一种方式。 – Patrick

回答

1

林不知道有你的方式解决。但为了简化您的代码并且还有一个默认值,您可以这样做:

根本没有必要拥有MyProperty文件。你可以删除它。

更新您的@Scheduled批注与此默认值:

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

这意味着,如果春天没有找到它采用了:后的默认值my.delay的属性。在你的情况下它的1000

而且,如果你想覆盖缺省值只添加属性在application.properties文件:

my.delay=5000 
3

您使用references a bean使用@beanName一个规划环境地政司表达式可以解决这个问题。

你会用这样的说法:

@Scheduled(fixedDelayString = "#{@myProperties.delay}") 

注意#{}使用(规划环境地政司表示),而不是${}(财产占位符)。

+0

我似乎无法完成这项工作,看起来像在评估'@ ConfigurationProperties' bean之前正在评估SPEL。有什么特别的我应该在'@Scheduled(fixedDelayString =?)'注释的SPEL中提供属性? –

+0

@SantiagoBaldrich这需要关于您项目设置的更多信息。请准备一个[Minimal,Complete和Verifiable示例](/ help/mcve)并发布一个新问题,我确定有人可以帮助 –

+0

完成:https://stackoverflow.com/questions/49034588/using-configurationproperties- IN-A-预定的注释按引用最BEA –

相关问题