2013-03-07 43 views
0

我有一系列扩展基本服务的服务。在这个基本服务中,我实例化一个类,用于轮询数据库并根据其内容发送通知,这个轮询的时间由Spring处理。我期望的是,对于扩展基本服务的每个服务应该有一个此轮询器的实例,但根据我放置@Scheduled注释的位置,它不起作用。当@Scheduled注释位于轮询类内时,Spring任务执行程序只创建一个实例

我想是这样的:

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 
    } 
} 

它按预期工作,但不符合设计目标。

有没有办法让计划的注释留在轮询中,同时确保每个扩展服务都得到它自己的实例?

回答

2

这是因为你的Poller类不是Spring管理的,其中Base是。 Pollernew运算符Base实例化,因此,Spring没有处理它。如果Spring不创建实例,那么它不会被Spring管理。

我认为你的设计一般是有缺陷的。你的孩子参考了孩子的基地和基地。对我来说,你似乎很难用这种方式创建多个子类。

如果你想有一个基类,我会推荐两件事之一。

  1. 继承。有Poller(以及其他子类)延伸Base
  2. 代表团。让Base成为每个孩子班的成员,并在孩子班中委托给它。

使用这些设计中的任何一种,我认为您可以让您的代码按预期工作。

相关问题