Spring @Scheduled cron details from property file - Exception

Chillax picture Chillax · Dec 10, 2015 · Viewed 8.4k times · Source

I was trying to define the cron details in my spring @Scheduled method

@Service
@PropertySource("classpath:application.properties")
public class CacheRefreshService {

@Scheduled(cron = "${api.refresh.cron}")
     public void refreshJob() throws Exception {
        LOGGER.info("Started Refresh");
        //do something
     }
}

And in my application.properties

#Refresh
api.refresh.cron =0 29 11 * * ?

When I define the cron details along with @Scheduled, it is running fine. But when I do this, it is not able to read the value from the properties file and the below error is thrown.

Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method 'refreshJob': Cron expression must consist of 6 fields (found 1 in "${api.refresh.cron}")

Any suggestions please?

Answer

Chillax picture Chillax · Dec 10, 2015

Adding the below to my ApplicationContext resolved the issue..

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
       return new PropertySourcesPlaceholderConfigurer();
    }