2014-09-09 3 views
3

Я пытаюсь использовать образец websocket, и здесь я получаю ошибку.Spring 4 @AutoWired Failed

`@Configuration 
@EnableWebSocketMessageBroker 
@EnableScheduling 
@Component 
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { 


     @Autowired 
     private SimpMessagingTemplate template; 

     private TaskScheduler scheduler = new ConcurrentTaskScheduler(); 


    @Override 
    public void registerStompEndpoints(StompEndpointRegistry registry) { 

     registry.addEndpoint("/simplemessages").withSockJS(); 
    } 

    /** 
    * Configure message broker options. 
    */ 
    @Override 
    public void configureMessageBroker(MessageBrokerRegistry config) { 

     config.enableSimpleBroker("/topic/", "/queue/"); 
     config.setApplicationDestinationPrefixes("/app"); 
    } 


    @PostConstruct 
    private void broadcastTimePeriodically() { 
     scheduler.scheduleAtFixedRate(new Runnable() { 
     public void run() { 

      template.convertAndSend("/topic/simplemessagesresponse", "Updated text "+new Date()); 


     } 
     }, 1000); 
    } 

    @Override 
    public void configureClientInboundChannel(ChannelRegistration registration) { 

    } 

    @Override 
    public void configureClientOutboundChannel(ChannelRegistration registration) { 
     registration.taskExecutor().corePoolSize(4).maxPoolSize(10); 
    } 

    @Override 
    public boolean configureMessageConverters(List<MessageConverter> arg0) { 
     // TODO Auto-generated method stub 
     return false; 
    } 

    @Override 
    public void configureWebSocketTransport(WebSocketTransportRegistration arg0) { 


    } 

} 

`

Вот мой Spring контекст XML

`

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/mvc 
         http://www.springframework.org/schema/mvc/spring-mvc.xsd       
         http://www.springframework.org/schema/beans      
         http://www.springframework.org/schema/beans/spring-beans.xsd 
         http://www.springframework.org/schema/context 
         http://www.springframework.org/schema/context/spring-context.xsd"> 



    <context:component-scan base-package="com.action" /> 

    <context:annotation-config/> 
    <!-- <annotation-driven /> --> 


</beans> 

`

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener 
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSocketConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.messaging.simp.SimpMessagingTemplate com.action.WebSocketConfig.template; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'brokerMessagingTemplate' defined in class path resource [org/springframework/web/socket/config/annotation/DelegatingWebSocketMessageBrokerConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.messaging.simp.SimpMessagingTemplate org.springframework.messaging.simp.config.AbstractMessageBrokerConfiguration.brokerMessagingTemplate()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'brokerMessageConverter' defined in class path resource [org/springframework/web/socket/config/annotation/DelegatingWebSocketMessageBrokerConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.messaging.converter.CompositeMessageConverter org.springframework.messaging.simp.config.AbstractMessageBrokerConfiguration.brokerMessageConverter()] threw exception; nested exception is java.lang.IllegalArgumentException: Converters must not be empty 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:326) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302) 

Любой может позволить мне знать, почему?

+0

могли бы вы добавить код класса SimpMessagingTemplate так, что это будет легко выяснить причину проблемы ... –

+0

также не-комментарий эта строка в вашем xml-файле Spring Spring Весной XML, приложение, управляемое аннотацией, включено в контейнер, объявив

+0

@AshishJagtap. Спасибо за рассмотрение моего вопроса. класс SImpMessaging ... не мой. это 'org.springframework.messaging.simp.SimpMessagingTemplate'. –

ответ

6

Ваш вопрос здесь:

@Override 
public boolean configureMessageConverters(List<MessageConverter> arg0) { 
     // TODO Auto-generated method stub 
     return false; 
} 

Я понимаю, что это автоматически сгенерированный код, но в моем тестовом случае с вашего образца я получаю эту StackTrace:

Caused by: java.lang.IllegalArgumentException: Converters must not be empty 
    at org.springframework.util.Assert.notEmpty(Assert.java:268) 
    at org.springframework.messaging.converter.CompositeMessageConverter.<init>(CompositeMessageConverter.java:43) 
    at org.springframework.messaging.simp.config.AbstractMessageBrokerConfiguration.brokerMessageConverter(AbstractMessageBrokerConfiguration.java:266) 

Это означает, что : или вы должны вернуть true из этого метода для регистрации преобразователей по умолчанию или добавить некоторые свои собственные преобразователи к этому List<MessageConverter>.

Когда я меняю его на возврат true все работает хорошо.

+0

ВЫ ХОРОШО .. СПАСИБО МНОГО .. ЭТО РАБОТАЕТ !!! –

+0

Кроме того, я обнаружил, что этот метод является новым и доступен в Spring 4.1. В версии 4.0.0 его там не было. Как только он был создан затмением, я оставил его как есть. Вы спасли весь мой день –

0

Я столкнулся с этой проблемой и провел прекрасные субботние вечерние часы, пытаясь понять это. Моя проблема заключалась в том, что я не включил конфигурацию websocket в корневую конфигурацию.

@Configuration 
@ComponentScan({ "xxx.yyy.controllers" }) 
@Import({SecurityConfig.class, WebSocketConfig.class}) 
public class RootConfig { 

} 

, а затем использовать его для приложений инициализаторе

public class WebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { 

    @Override 
    protected Class<?>[] getRootConfigClasses() { 
     return new Class[] { RootConfig.class }; 
    } 

    @Override 
    protected Class<?>[] getServletConfigClasses() { 
     return new Class[] { AppConfig.class }; 
    } 

    @Override 
    protected String[] getServletMappings() { 
     return new String[] { "/" }; 
    } 
}