Search code examples
springinheritanceannotationsaopscheduler

Spring @Scheduled Annotation for Inherited Classes


I am trying to use @Scheduled annotation for a service layer class. The class also gets monitored by a logging service through AOP.

When I make the service class implement an interface, Spring throws the error

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

This is the service layer class:

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

If I remove the inheritance, it works without problem. Why is that?

This is what I have for the logging service :

@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 {
        .....

Solution

  • You have several options here:

    • Add run() to DummyI interface

    • Create another interface having only run() method (or use java.lang.Runnable) and implemented that interface as well:

      public class DummyService implements DummyI, Runnable
      
    • Enable class based () proxies