I'm using a @ConfigurationProperties to define the property my.delay
.
@ConfigurationProperties( "my" )
public class MyProperties {
private long delay = 1000L;
public long getDelay() {
return delay;
}
public void setDelay(long delay) {
this.delay = delay;
}
}
In the scheduler method I try to use 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" );
}
}
Then the following error arises:
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]
You can solve it using a SpEL expression that references a bean using @beanName
.
You would use it that way:
@Scheduled(fixedDelayString = "#{@myProperties.delay}")
Notice that #{}
is used (SpEL expression) instead of ${}
(property placeholder).
Im not sure if there is a solution for your approach. But to simplify your code and also have a default value you can go like that:
No need to have MyProperty
file at all. You can delete it.
Update your @Scheduled
annotation with this default value:
@Scheduled( fixedDelayString = "${my.delay:1000}" )
This means if Spring does not find a property of my.delay
it uses the default value after the :
. In your case its 1000
.
And if you like to override the default value just add the property in your application.properties
file:
my.delay=5000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With