Reputation: 331
I've been trying to set the cron property of @Scheduled as below.
public class ObjectScheduler {
@Value("${config.cron.expression}")
private static final CRON_EXPRESSION;
@Scheduled(cron = CRON_EXPRESSION, zone="GMT")
public void scheduledObjectFetch() {...}
}
I'm getting a compile time error here saying
The value for the annotation attribute Scheduled.cron attribute must be a constant expression.
The same thing works if I give the expression in the attribute directly
@Scheduled(cron = "${config.cron.expression}", zone="GMT")
Here also the value is being assigned at runtime from the config so why doesn't it give a compile time error here? Why is it that when I assign it to a variable using the @Value annotation does it not consider it be a constant expression? Is there something I'm missing? Is it due to Java or Spring's @Value annotation?
Upvotes: 0
Views: 4075
Reputation: 6216
In your case you made the field as final
the most fundamental reason you are not able to inject value into the field using the @value
is that Java replaces static final "variable" occurrences in the code with the actual values (since it's of course known at compile time). So if you remove the final
qualifier it should work for you using spring setter
injection. You cannot use @value to inject value from a property file into a static final
variable, it's beccause of how java handles final static variables.
Ideally we could use the spring expression to populate cron from the property
file by providing it like :
@Component("scheduledAnnotationObjectScheduler")
public class ObjectScheduler {
@Scheduled(cron = "${cron.expression}")
public void scheduledObjectFetch() {...}
}
application.properties
cron.expression=0 15 10 15 * ?
This should resolve the cron
value from the property file in theory since it is picked up during component scanning.
Upvotes: 1
Reputation: 19545
Spring does not insert @Value
into static fields though it can be done via a setter.
And this is also applied to static final
fields which need to be defined at compile time.
So you could not configure CRON_EXPRESSION
via @Value
, it could work only if you set it hardcoded:
private static final String CRON_EXPRESSION = "0 0 8 * * ?";
@Scheduled(cron = CRON_EXPRESSION, zone="GMT")
public void scheduledObjectFetch() {...}
Upvotes: 1