Spring @Scheduled Annotation for Inherited Classes

时间:2012-05-16 20:59:12

标签: spring inheritance annotations aop scheduler

我正在尝试将@Scheduled注释用于服务层类。该类还通过AOP由日志记录服务进行监视。

当我使服务类实现一个接口时,Spring会抛出错误

Error creating bean with name 'dummyService' defined in file
......
......
Caused by: java.lang.IllegalStateException: failed to prepare task
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor$1.doWith(ScheduledAnnotationBeanPostProcessor.java:114)
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:452)
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:430)
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.postProcessAfterInitialization(ScheduledAnnotationBeanPostProcessor.java:98)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:407)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1426)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    ... 11 more
Caused by: java.lang.NoSuchMethodException: $Proxy23.run()
    at java.lang.Class.getMethod(Class.java:1605)
    at org.springframework.util.MethodInvoker.prepare(MethodInvoker.java:178)
    at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor$1.doWith(ScheduledAnnotationBeanPostProcessor.java:111)
    ... 17 more

这是服务层类:

package com.mydomain.web.myapp.service;
@Service
public class DummyService implements DummyI{
        @Scheduled(cron = "${some.cron.time}")
        public void run() {
        }
}

如果我删除了继承,它可以正常工作。这是为什么?

这就是我对日志记录服务所拥有的:

@Component
@Aspect
public class LoggingServiceImpl implements LoggingService {
        private final Logger log = LoggerFactory.getLogger(this.getClass());
        @Around("execution(* com.mydomain.web.myapp..*.*(..))")
        public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        .....

1 个答案:

答案 0 :(得分:1)

这里有几个选项:

  • run()添加到DummyI界面

  • 创建另一个只有run()方法的接口(或使用java.lang.Runnable)并实现该接口:

    public class DummyService implements DummyI, Runnable
    
  • 启用基于类()代理