복붙노트

[SPRING] @ServerEndpoint 및 @Autowired

SPRING

@ServerEndpoint 및 @Autowired

어떻게하면 @ServerEndpoint에 필드를 자동으로 추가 할 수 있습니까? 다음은 작동하지 않습니다.

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

그러나 @ServerEndpoint 제거하면 잘 작동합니다.

나는 스프링 3.2.1과 자바 7을 사용하고있다.

해결법

  1. ==============================

    1.그것은 당신이 봄과 Java WebSocket API를 통합하려고하는 것 같습니다. @Component로 주석 처리 된 클래스는 스프링 빈에 등록되고 인스턴스는 기본적으로 스프링에 의해 싱글 톤으로 관리됩니다. 그러나 @ServerEndpoint로 주석 된 클래스는 서버 측 WebSocket 끝점에 등록되며 해당 끝점의 WebSocket이 서버에 연결될 때마다 해당 인스턴스가 JWA 구현에 의해 만들어지고 관리됩니다. 따라서 두 주석을 함께 사용할 수는 없습니다.

    그것은 당신이 봄과 Java WebSocket API를 통합하려고하는 것 같습니다. @Component로 주석 처리 된 클래스는 스프링 빈에 등록되고 인스턴스는 기본적으로 스프링에 의해 싱글 톤으로 관리됩니다. 그러나 @ServerEndpoint로 주석 된 클래스는 서버 측 WebSocket 끝점에 등록되며 해당 끝점의 WebSocket이 서버에 연결될 때마다 해당 인스턴스가 JWA 구현에 의해 만들어지고 관리됩니다. 따라서 두 주석을 함께 사용할 수는 없습니다.

    어쩌면 가장 간단한 해결 방법은 Spring 대신 CDI를 사용하는 것입니다. 물론 서버가 CDI를 지원해야합니다.

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

    가능하지 않은 경우 ServerEndpointConfig.Configurator 버전을 사용하여 ServerEndpoint로 주석 된 클래스의 인스턴스화 프로세스를 가로 챌 수 있습니다. 그런 다음, 직접 클래스를 인스턴스화하고 BeanFactory 또는 ApplicationContext의 인스턴스를 사용하여 클래스를 autowire 할 수 있습니다. 실제로,이 사용법에 이미 유사한 응답이 있습니다. 이 질문과 Martins의 작업 예제 (특히 Spring과의 통합을위한 사용자 정의 된 구성 프로그램)를 참조하십시오.

  2. ==============================

    2.이 문제는 SpringConfigurator (spring 4)를 사용하여 수정할 수 있습니다.

    이 문제는 SpringConfigurator (spring 4)를 사용하여 수정할 수 있습니다.

    서버 구성 요소에 ServerEndpoint를 추가하십시오.

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

    필수 종속성 :

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

    3.실제로 이것을 클래스에 실제로 추가 할 수 있어야합니다.

    실제로 이것을 클래스에 실제로 추가 할 수 있어야합니다.

    @PostConstruct
    public void init(){
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }
    
  4. ==============================

    4.내 솔루션은 다음과 같습니다.

    내 솔루션은 다음과 같습니다.

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

    여기서 Spring ApplicationListener는 컨텍스트를 정적 변수에 저장하는 ApplicationContextAware입니다.

  5. ==============================

    5.JavaEE 7 사양에 따르면

    JavaEE 7 사양에 따르면

    @ServerEndpoint
    The annotated class must have a public no-arg constructor.
    
  6. from https://stackoverflow.com/questions/29306854/serverendpoint-and-autowired by cc-by-sa and MIT license