Spring Controller实现ApplicationListener

时间:2014-07-30 04:13:32

标签: java spring spring-websocket

我在Spring 4.0.5中实现了WebSocket。客户端(浏览器)保持与服务器的连接。当我的服务层在后端更新一些记录时,我想通知客户哪个订阅了特定主题。

我希望我的Controller能够监听我的ApplicationEvent并将其发布到WebSocket客户端。这可能吗?

我在服务层实现了另一个侦听器,它可以捕获事件。 控制器是否无法侦听ApplicationEvent?

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import com.geneoz.service.event.MessageEvent;

@Controller
public class ApplicationEventObservorController implements ApplicationListener<MessageEvent> {

    private static Logger logger = Logger.getLogger(ApplicationEventObservorController.class);

    private SimpMessagingTemplate template;

    @Autowired
    public ApplicationEventObservorController(SimpMessagingTemplate template) {
        logger.debug("Initialising ApplicationEventObservorController");
        this.template = template;
    }

    @Override
    public void onApplicationEvent(MessageEvent event) {
        logger.debug("Captured event. " + event);
        this.template.convertAndSend("/topic/update", event.toString());
    }

}

0 个答案:

没有答案