gpt4 book ai didi

spring - 无法在 @Scheduled 注释中使用 @ConfigurationProperties

转载 作者:行者123 更新时间:2023-12-04 08:44:14 26 4
gpt4 key购买 nike

我使用@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]

最佳答案

您可以使用 references a bean 的 SpEL 表达式来解决它。使用 @beanName .

你会这样使用它:

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

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

关于spring - 无法在 @Scheduled 注释中使用 @ConfigurationProperties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42251225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com