Java 当@Scheduled注释放置在轮询类中时,Spring任务执行器仅创建一个实例
我有一系列扩展基本服务的服务。在这个基本服务中,我实例化了一个类,该类用于轮询数据库并根据其内容发送通知,轮询的时间由spring处理。我所期望的是,对于扩展基本服务的每个服务,都应该有一个轮询器实例,但是根据我放置@Scheduled注释的位置,它不起作用 我想要的是:Java 当@Scheduled注释放置在轮询类中时,Spring任务执行器仅创建一个实例,java,spring,task,Java,Spring,Task,我有一系列扩展基本服务的服务。在这个基本服务中,我实例化了一个类,该类用于轮询数据库并根据其内容发送通知,轮询的时间由spring处理。我所期望的是,对于扩展基本服务的每个服务,都应该有一个轮询器实例,但是根据我放置@Scheduled注释的位置,它不起作用 我想要的是: public class Base { private Poller p = new Poller(this); // the rest of the service code } public class
public class Base {
private Poller p = new Poller(this);
// the rest of the service code
}
public class Poller{
Base b;
public Poller(Base B){
b=B;
}
@Scheduled(fixedDelay=5000)
public void poll(){
//do stuff
System.out.println(b.name); //doesn't work, causes really unhelpful errors
System.out.println("----"); //prints as expected, but only once
//regardless of how many extending services exist
}
}
但它似乎只在所有扩展器之间实例化一个轮询器。如果我这样构造它:
public class Base {
private Poller p = new Poller(this);
// the rest of the service code
@Scheduled(fixedDelay=5000)
public void poll(){
p.poll();
}
}
public class Poller{
Base b;
public Poller(Base B){
b=B;
}
public void poll(){
//do stuff
System.out.println(b.name); //prints the name of the service for each extender
System.out.println("----"); //prints as expected, once for each extender
}
}
它按预期工作,但与此处的设计目标不符
有没有一种方法可以让定时注释留在轮询器中,同时确保每个扩展服务都有它自己的实例?这是因为您的
Poller
类不是Spring管理的,而Base
是Poller
在Base
中用new
操作符实例化,因此Spring对其没有句柄。如果Spring没有创建实例,那么它就不会被Spring管理
我认为你的设计总的来说是有缺陷的。您的孩子有一个对基的引用,基是对孩子的引用。在我看来,你可能很难用这种方式创建多个子类
如果你想有一个基类,我推荐两件事中的一件
Poller
(以及其他子类)扩展Base
Base
成为每个子类的成员,并在子类中委托给它