简体   繁体   English

Spring Boot如何识别子类方法上的@Scheduled?

[英]How does Spring Boot recognize @Scheduled on a subclass' method?

Let's take an example of a simple Spring Boot program: 让我们以一个简单的Spring Boot程序为例:

Application.java 应用程序

@SpringBootApplication
@EnableScheduling
public class Application {

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

SuperClass.java 超类.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. 根据答案,子类将仅继承由@Inherited注释的注释,而@Scheduled没有此类注释。 So how come this is working? 那么这怎么起作用呢?

@Inherited only applies to class types, not methods. @Inherited仅适用于类类型,不适用于方法。

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. 当Spring扫描bean中的@Scheduled注释(或其他注释)时,它将在bean类中查找所有方法。 SubClass has a printSomething so Spring decides it can enhance it with the scheduling behavior. SubClass具有printSomething因此Spring决定可以通过调度行为来增强它。


Spring handles @Scheduled a little differently than the standard proxying mechanism and is able to invoke private methods annotated with it. Spring处理@Scheduled的方式与标准代理机制略有不同,并且能够调用带有注释的private方法。

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. 如果您重写了子类中的printSomething方法,并在该声明上省略了@Scheduled注释,那么Spring将不会应用调度行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM