@Configuration 类中的 Spring @Scheduled

fel*_*gao 5 java spring scheduling

当我运行以下类时,Spring 不会调度方法“mywork()”。

@Configuration
@EnableScheduling
public class AppConfig {

    @Scheduled(fixedRate = 1000)
    public void mywork(){
        System.out.println("test");
    }

    @Bean(name = "propertyConfigurer")
    public PropertyPlaceholderConfigurer propertyConfigurer(){
        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        return ppc;
    }

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是如果我删除propertyConfigurer的Bean定义,它就会正常工作。

@Configuration
@EnableScheduling
public class AppConfig {

    @Scheduled(fixedRate = 1000)
    public void mywork(){
        System.out.println("test");
    }

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

谁能告诉我为什么?

Ran*_*niz 3

正如评论中所指出的,这是因为您正在配置 bean 中执行应用程序逻辑。

带有注释的类@Configuration就是配置,这些是旧 XML 配置的代码等效项,并且应该只包含用于设置应用程序的代码。

重复任务和功能应该位于用 注释的类(或包含诸如或 之类@Component的元注释)的内部,或者从用 注释的方法实例化的类,或以其他方式在上下文中注册的类。@Component@Controller@Service@Bean

现在,为什么当你的配置中有一个 bean 方法时它不起作用:

可能正如 M. Deinum 所说,这是因为您的类正在被代理,但 Spring 可以轻松找到@Scheduled已代理的常规 bean 上的注释,所以我怀疑是这样。

更可能的原因是,@Bean注释使Spring将您的配置类视为应用程序连接的一部分(这是有道理的 - 这就是它应该的样子),因此它可能是在之前创建的,这ScheduledAnnotationBeanPostProcessor当然意味着后处理器永远不会看到@Scheduled配置类上的注释,因此永远不会向调度程序注册它。

长话短说

不要将应用程序逻辑放入配置中。