Spring @Configuration(非xml配置)用于注释驱动的任务

Dav*_* L. 7 spring annotations spring-mvc scheduled-tasks

任何人都可以解释如何在没有任何XML配置的情况下使用@Scheduled注释实现任务的基本配置吗?我可以找到的所有示例至少使用最小的XML配置.例如:

http://blog.springsource.com/2010/01/05/task-scheduling-simplifications-in-spring-3-0/

这使用典型的:

  <context:component-scan base-package="org/springframework/samples/task/basic/annotation"/> 
  <task:annotation-driven/>
Run Code Online (Sandbox Code Playgroud)

所以我只是使用@Configuration注释和一堆@Bean注释.它们都是在启动时实例化的,但是@Scheduled的那个没有运行.我在过去使用XML配置时成功使用了该注释,但从未使用过注释.

小智 16

只需在WebMvcConfig类上添加@EnableScheduling即可

@Configuration
@EnableWebMvc
@EnableAsync
@EnableScheduling
public class WebMvcConfig extends WebMvcConfigurerAdapter {
   /** Annotations config Stuff ... **/
}
Run Code Online (Sandbox Code Playgroud)

  • 是的问题是在Spring 3.1可用之前. (2认同)

Kev*_*vin 4

<task:annotation-driven />注释最终声明一个 ScheduledAnnotationBeanPostProcessor 来读取代码中的 @Scheduled 注释。请参阅此处: http: //static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessor.html

这样就可以处理好<task:annotation-driven />线路了。要进行组件扫描,您需要使用 AnnotationConfigApplicationContext。但不确定它是否/如何与 Web 容器一起使用。