当我在没有实现CommandLineRunner的情况下运行我的任务并添加@Scheduled注释时,似乎正在关闭上下文。如何保持上下文打开以便@Scheduled可以正常运行?
DataTransferTask.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DataTransferTask {
public static void main(String[] args) {
SpringApplication.run(DataTransferTask.class, args);
}
}
DataTransferRunner.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.task.configuration.EnableTask;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@EnableTask
@EnableScheduling
public class DataTransferRunner {
@Autowired
public DataTransferRunner() {
}
@Scheduled(fixedRateString = "${job_concurrency.fixed-rate}")
public void run() throws Exception {
System.out.println("I started running");
}
}
以下是我不断获得的例外
Caused by: java.lang.IllegalStateException: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@21526f6c has been closed already
at org.springframework.context.support.AbstractApplicationContext.assertBeanFactoryActive(AbstractApplicationContext.java:1065) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBeanNamesForType(AbstractApplicationContext.java:1176) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.cloud.task.batch.configuration.TaskBatchExecutionListenerBeanPostProcessor.postProcessAfterInitialization(TaskBatchExecutionListenerBeanPostProcessor.java:59) ~[spring-cloud-task-batch-1.2.0.RELEASE.jar:1.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:423) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1633) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
... 73 common frames omitted
答案 0 :(得分:2)
由于你有@EnableTask,一旦所有内容都运行完毕,spring将关闭上下文。从代码看起来你没有明确地运行任何东西,所以spring在你的@Schedule()注释开始之前关闭了上下文。
对此的解决方法是告诉spring不要使用spring.cloud.task.closecontext_enable=false
关闭上下文。这将使您的计划任务的上下文保持打开状态。
这里有一些文档:https://docs.spring.io/spring-cloud-task/docs/1.2.2.RELEASE/reference/htmlsingle/#features-lifecycle
关于该物业的另一个说明。它在文档中显示closecontext_enable
但在检查了日志和jar之后,该属性已被弃用并被close_context_enabled
替换。