2

Let's take an example of a simple Spring Boot program:

Application.java

@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class);
    }
}

SuperClass.java

public abstract class SuperClass {

    @Scheduled(fixedRate = 5000)
    public void printSomething() {
        System.out.println("this is the super method");
    }
}

SubClass.java

@Component
public class SubClass extends SuperClass {

}

According to this answer, only annotations annotated by @Inherited are inherited by subclasses, and @Scheduled does not have such an annotation. So how come this is working?

Community
  • 1
  • 1
unlimitednzt
  • 1,035
  • 2
  • 16
  • 25

1 Answers1

8

@Inherited only applies to class types, not methods.

Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect.

When Spring scans beans for the @Scheduled annotation (or others), it looks for all methods in the bean class. SubClass has a printSomething so Spring decides it can enhance it with the scheduling behavior.


Spring handles @Scheduled a little differently than the standard proxying mechanism and is able to invoke private methods annotated with it.

Had you overriden the printSomething method in the subclass and omitted the @Scheduled annotation on that declaration, Spring would not have applied the scheduling behavior.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • I see. So in the answer I've linked to, the foo() method wasn't invoked because it had overridden the super method. Thanks for the clarification. – unlimitednzt Jan 27 '17 at 16:59