20

I am configuring Websockets in Spring basically by following the guide provided in the documentation.

I am currently trying to send a message from the server to the client as explained in the section "Sending messages from anywhere"

Following the example, you can Autowire a class called SimpMessagingTemplate

@Controller
public class GreetingController {

    private SimpMessagingTemplate template;

    @Autowired
    public GreetingController(SimpMessagingTemplate template) {
        this.template = template;
    }

    @RequestMapping(value="/greetings", method=POST)
    public void greet(String greeting) {
        String text = "[" + getTimestamp() + "]:" + greeting;
        this.template.convertAndSend("/topic/greetings", text);
    }

}

However, my current project cannot find the bean "SimpMessagingTemplate". (Intellij: 'Could not autowire. No beans of SimpMessagingTemplate type found'.

I have check several examples in the internet but I cannot find how to get Spring to create an instance of SimpMessagingTemplate. How can I Autowire it ?

EDIT:

I decided to send some more background information. This is my current websocket configuration:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:websocket="http://www.springframework.org/schema/websocket"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/websocket
        http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd">

        <!-- TODO properties to be read from a properties file -->
        <websocket:message-broker application-destination-prefix="/app">
            <websocket:stomp-endpoint path="/new_session" >
                <websocket:sockjs/>
            </websocket:stomp-endpoint>
            <websocket:simple-broker prefix="/topic"/>
        </websocket:message-broker>
</beans>

Websocket works with this controller

@Controller
public class SessionController {

    private static final Logger log = LoggerFactory.getLogger(SessionController.class);

    @MessageMapping("/new_session")
    @SendTo("/topic/session")
    public SessionStatus newSession(Session session) throws Exception {
    Thread.sleep(3000); // simulated delay
    log.info("Response sent !!");
    return new SessionStatus("StatusReport, " + session.toString() + "!");
    }
}

I just not sure how to to make this work

public class SessionController {

    private static final Logger log = LoggerFactory.getLogger(SessionController.class);

    private SimpMessagingTemplate template;

    @Autowired
    public SessionController(SimpMessagingTemplate template) {
    this.template = template;
    }

}

As the bean "SimpMessagingTemplate template" is not found. Spring documentation does not offer more details regarding this matter.

EDIT: Example of working code in github

Tk421
  • 6,196
  • 6
  • 38
  • 47

4 Answers4

19

I had the same problem, the error occurred because my websocket config file:

@Configuration
@EnableWebSocketMessageBroker
@EnableScheduling
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

}

was not scanned by spring.

so the fix was to add the package with this configuration file to the scanned packages.

Urbanleg
  • 6,252
  • 16
  • 76
  • 139
6

Strange, because when you use the websocket namespace, the "message-broker" element causes the creation of a SimpMessagingTemplate bean which should then be available for you to inject. Are both the controller and the websocket namespace in the same ApplicationContext or is perhaps one in the "root" context and the other in the DispatcherServlet context?

Rossen Stoyanchev
  • 4,910
  • 23
  • 26
  • 2
    Thanks for your help. I found the problem. I wrote a [proof of code](https://github.com/tk421/spring-stomp) and then I realize that the problem is that Intellij is not picking up the @Autowire for SimpMessagingTemplate properly. If you run the program now it works just fine. – Tk421 Apr 14 '14 at 22:46
  • 2
    @plkmthr The issue is Intellij not picking up properly SimpMessagingTemplate. If you run it will work. Check the link to the "proof of code" – Tk421 Jan 06 '15 at 01:35
  • Right now I am suppressing the warnings for all the classes which are trying to autowire. But I don't like that. – systemhalted Jan 14 '15 at 07:11
  • 1
    Isn't work if suppressed. With exception: `Parameter 0 of constructor in com.example.socketdemo.controllers.DemoController required a bean of type 'org.springframework.messaging.simp.SimpMessagingTemplate' that could not be found.` – qwert_ukg Mar 02 '19 at 09:12
5

You shall either have a bean definition id with same name as class name in your applicationContext xml or annotate @Component on injecting class for Autowire to work

<bean id="SimpMessagingTemplate " class="your-class" >

You may need to define below tag pointing to your package for later case

<context:component-scan base-package="com.x.y"/>
earthling
  • 69
  • 3
  • 5
    Please note that SimpMessagingTemplate is not my class is part of the spring Framework. The documentation does not give more information about how to get an instance of that class. If I try to add the bean in my XML like is expecting a parameter in the constructor (MessageChannel interface) which I am not sure how to link to the current websocket configuration. – Tk421 Apr 09 '14 at 00:11
  • I have more question related with this issue. http://stackoverflow.com/questions/23026408/how-to-use-executorsubscribablechannel – Tk421 Apr 12 '14 at 05:16
1

Rossen was correct. The addition of the element will add the SimpMessagingTemplate bean to the context for injection. This has to be in the web app root context, not the context for Spring DispatchServlet. E.g., in the following web.xml file, the message-broker element should be included in app-root.xml file. Including only in app-mvc.xml will cause NoSuchBeanDefinitionException.

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/app-root.xml</param-value>
</context-param>

<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/spring/app-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
raymond
  • 21
  • 1