@ServerEndpoint and @Autowired

How can I autowire a field in @ServerEndpoint. Does not work.

@Component
@ServerEndpoint("/ws")
public class MyWebSocket {   
    @Autowired
    private ObjectMapper objectMapper;
}

However, if I delete @ServerEndpoint, it works fine.

I am using spring 3.2.1 and Java 7

+4
source share
5 answers

, Spring Java WebSocket API. , @Component, Spring bean, Spring . , @ServerEndpoint, WebSocket , , WebSocket , JWA. .

, CDI Spring. , CDI.

@ServerEndpoint("/ws")
public class MyWebSocket {   
    @Inject
    private ObjectMapper objectMapper;
}

, , ServerEndpoint, ServerEndpointConfig.Configurator. autowire BeanFactory ApplicationContext. , . . Martins (, Configurator Spring).

+5

​​ SpringConfigurator (spring 4):

ServerEndpoint:

@ServerEndpoint(value = "/ws", configurator = SpringConfigurator.class)

maven:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>${spring.version}</version>
</dependency>
+3

.

@PostConstruct
public void init(){
    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
+2

:

public WebsocketServletTest() {
      SpringApplicationListener.getApplicationContext().getAutowireCapableBeanFactory().autowireBean(this);
}

SpringApplicationListener ApplicationContextAware,

+1

JavaEE 7

@ServerEndpoint
The annotated class must have a public no-arg constructor.
0

All Articles