2013-11-22 31 views
0

我試圖使用cometd作爲servlet來dropwizard,但BayeuxServer似乎沒有在我的服務中注入。我將我的兩個Servlet作爲這樣(請注意,我沒有使用web.xml所以我定義PARAMS自己):在dropwizard中使用cometd

cometdConfig.put("services", MyService.class.getCanonicalName()); 

System.out.print("OrderService name: " + MyService.class.getCanonicalName()); 

environment.addServlet(AnnotationCometdServlet.class, "/cometd/*").addInitParams(cometdConfig).setInitOrder(1); 
environment.addServlet(new MyServiceServlet(), "/orders/*").setInitOrder(2); 

我的服務(這是我的代碼失敗):

public class MyService 
implements MyWatcher.Listener 
{ 
    @Inject 
    private BayeuxServer bayeuxServer; 
    @Session 
    private LocalSession sender; 

    private final String _channelName; 

    private ServerChannel _channel = null; 

    public OrderService() { 
     _channelName = "/cometd/"; 
     initChannel(); 
    } 

    private void initChannel() { 
     // I get an NPE here 
     bayeuxServer.createIfAbsent(_channelName, new ConfigurableServerChannel.Initializer() { 
     @Override 
     public void configureChannel(ConfigurableServerChannel channel) { 
      // ... 
     } 
     }); 
    _channel = bayeuxServer.getChannel(_channelName); 
    } 
} 

我也試圖創造我自己的BayeuxServer的實例,但隨後導致單獨的NPE在BayeuxServerImpl.freeze();

任何人都知道如何正確使用的cometd與dropwizard?

+0

不要使用'Class.getCanonicalName()',因爲我認爲它會破壞內部類的類加載。改爲使用'Class.getName()'。 – sbordet

回答

3

爲了注入BayeuxServer實例,CometD必須有要注入的服務實例,在這種情況下,您的類MyService的實例。

不幸的是,從構造(我想你上面名不副實,稱這是OrderService)您所呼叫的initChannel()方法,該方法嘗試使用BayeuxServer領域還未被注入,因爲構造仍在執行。

解決的辦法是你的通道初始化推遲與@PostConstruct註解不同的方法:

public class MyService 
{ 
    @Inject 
    private BayeuxServer bayeuxServer; 
    @Session 
    private LocalSession sender; 
    private final String _channelName; 
    private ServerChannel _channel; 

    public MyService() 
    { 
     _channelName = "/cometd/"; 
    } 

    @PostConstruct 
    private void initChannel() 
    { 
     _channel = bayeuxServer.createChannelIfAbsent(_channelName).getReference(); 
    } 
} 

使用的API的cometd是的cometd 2.7.0,我建議,如果你是在舊的cometd版本使用。

+0

謝謝,我試過使用'@ PostConstruct',但我仍然得到NPE。當我檢查時,'bayeuxServer'仍然爲空,儘管它現在正在稍後調用。 –

+0

我發現我錯過的一件事不是用'@ Service'註釋我的服務。我再次嘗試沒有使用@ PostConstruct,它仍然失敗,所以我仍然需要它。非常感謝! –