预计单个匹配bean但找到2

时间:2016-10-19 10:25:14

标签: java spring websocket

我正在使用websocket从服务器向客户端发送消息。当我将此代码添加到控制器中时:

private SimpMessagingTemplate template;

@Autowired
public InstanceMessageController(SimpMessagingTemplate template) {
     this.template = template;
}
像这样:

   @Controller    
   public class InstanceMessageController {     

    private SimpMessagingTemplate template;

    @Autowired
    public InstanceMessageController(SimpMessagingTemplate template) {
        this.template = template;
    }
    @MessageMapping("/vehicle/status")
    @SendTo("/topic/status")
    public void subscribeVehicleStatus(HelloMessage message) throws Exception {
        try {
            for (int i = 0; i < 10; i++) {
                //template.convertAndSend("/topic/location", "aaaaaaa");
            }
        } catch (Exception e) {
            log.error(e);
        }
    }
}

抛出错误:

       [ERROR]-[2016年-10月-19日17:53:25.026]-[RMI TCP Connection(2)-127.0.0.1]-[org.springframework.web.context.ContextLoader]-
{Context initialization failed}
                org.springframework.beans.factory.UnsatisfiedDependencyException: 
        Error creating bean with name 
        com.zw.socket.service.controller.InstanceMessageController0 defined in class path resource [spring-config/spring-socket-servlet.xml]: 
    Unsatisfied dependency expressed through constructor parameter 0; 
    nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: 
    No qualifying bean of type [org.springframework.messaging.simp.SimpMessagingTemplate] is defined: 
    expected single matching bean but found 2:org.springframework.messaging.simp.SimpMessagingTemplate#0,brokerMessagingTemplate

删除第一个代码片段时,程序运行正常。哪里出错了?春季版:4.0.4.RELEASE。我该怎么办? bean配置:

<bean class="com.zw.socket.service.controller.InstanceMessageController"></bean>

1 个答案:

答案 0 :(得分:0)

检查配置文件(例如:spring-socket-servlet.xml)是否已经重复配置:

<websocket:message-broker application-destination-prefix="/app">
    <websocket:stomp-endpoint path="/vehicle">
        <websocket:handshake-interceptors>
            <bean class="org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor"/>
        </websocket:handshake-interceptors>
        <websocket:sockjs session-cookie-needed="true" />
    </websocket:stomp-endpoint>
    <websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>

如果配置文件和代码都给出。这将导致2 SimpMessagingTemplate实例。删除XML配置,将修复它。