Выражение Cron должно состоять из 6 полей (найдено 1 в "${cron.expression}"), частично исправлено, но имеет проблемы с AnnotationConfigApplicationContext.

Я пытаюсь параметризовать выражение 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 * * * * ?


person Hemal    schedule 30.04.2017    source источник
comment
Вы знаете, как создать веб-приложение? Если нет, вы можете проверить первые два шага из это руководство для простого примера. Если у вас есть веб-приложение, вам нужно добавить весенние зависимости в pom.xml и указать весенний контекст в web.xml, для последнего проверьте этот вопрос.   -  person mczerwi    schedule 01.05.2017
comment
Червински, я знаю, как создать веб-приложение. Мое приложение не имеет графического интерфейса, оно обрабатывает сообщения через MDB и делает вызов веб-сервиса. Если есть сбои в вызове веб-службы, вместо того, чтобы иметь очередь ошибок для повторной обработки этих сообщений, я хочу, чтобы планировщик весны запускался каждые 4 часа, который запускает вызов веб-службы. У меня этот процесс работает. Я хочу переместить выражение cron в файл свойств и столкнуться с проблемами в этом процессе.   -  person Hemal    schedule 01.05.2017
comment
Я до сих пор не совсем понимаю, с какими проблемами вы столкнулись. Ваши файлы applicationContext.xml и application.properties находятся в пути к классам, когда вы запускаете приложение на сервере? Если они есть и контекст создан правильно (посмотрите на последнюю ссылку в первом комментарии), то ваш планировщик должен работать нормально.   -  person mczerwi    schedule 01.05.2017
comment
Проблема заключалась в неправильном создании экземпляра контекста. Я соответствующим образом изменил свой код, и он работает. Я опубликую обновленный код.   -  person Hemal    schedule 01.05.2017


Ответы (1)


Вот как я заставил это работать

Application-context.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">


    <context:property-placeholder properties-ref="applicationProps"  />
    <context:annotation-config/>
    <context:component-scan base-package="com.hemal.spring" />
    <task:annotation-driven />
</beans>

MyApplicationConfig.java

package com.hemal.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@EnableScheduling
@ComponentScan(basePackages = {"com.hemal.spring"})
@PropertySource("classpath:application.properties")
public class MyApplicationConfig {

    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();

        properties.setLocation(new ClassPathResource( "application.properties" ));
        properties.setIgnoreResourceNotFound(false);

        return properties;
    }
}

MyApplicationContext.java

пакет com.hemal.spring;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

public class MyApplicationContext implements WebApplicationInitializer{

    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(MyApplicationConfig.class);


        servletContext.addListener(new ContextLoaderListener(rootContext));
    }
}

Мой класс планировщика

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.ClassPathXmlApplicationContext;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;


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();
        }
    }
}

application.properties cron.expression=0/5 * * * * ?

person Hemal    schedule 05.05.2017