Я пытаюсь параметризовать выражение cron и читать его из файла свойств. Во время этого процесса я получаю следующее исключение: «Ошибка создания bean-компонента с именем« springScheduleCronExample »: инициализация bean-компонента не удалась; вложенным исключением является java.lang.IllegalStateException: обнаружен недопустимый метод @Scheduled« cronJob »: выражение Cron должно состоять из 6 полей (найдено 1 в "${cron.expression}")".
Затем я нашел следующее сообщение
Используя это выражение, я cron читается, только если у меня есть
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( SpringScheduleCronExample.class);
определить в моем основном методе. Проблема, с которой я столкнулся, заключается в том, что я хочу запустить это на сервере без основного метода, может ли кто-нибудь помочь мне с этим.
Вот мой applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<task:annotation-driven />
<util:properties id="applicationProps" location="application.properties" />
<context:property-placeholder properties-ref="applicationProps" />
<bean class="com.hemal.spring.SpringScheduleCronExample" />
</beans>
Мой SpringScheduleCronExample.java выглядит так
package com.hemal.spring;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@Configuration
@EnableScheduling
@PropertySource("classpath:application.properties")
public class SpringScheduleCronExample {
private AtomicInteger counter = new AtomicInteger(0);
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Scheduled(cron = "${cron.expression}")
public void cronJob() {
int jobId = counter.incrementAndGet();
System.out.println("Job @ cron " + new Date() + ", jobId: " + jobId);
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SpringScheduleCronExample.class);
try {
Thread.sleep(24000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
context.close();
}
}
}
В свойствах моего приложения есть cron.expression=*/5 * * * * ?
applicationContext.xml
иapplication.properties
находятся в пути к классам, когда вы запускаете приложение на сервере? Если они есть и контекст создан правильно (посмотрите на последнюю ссылку в первом комментарии), то ваш планировщик должен работать нормально. - person mczerwi   schedule 01.05.2017