@ServerEndpointで@Autowiredを使用する方法 - Javaの春ブーツ?

ワイン:

私はこのトピックに関する質問がたくさんある知っています。私は春ブーツドキュメントと、ここでのソリューションのすべてを読みました。春ブーツドキュメントによると、@ServerEndpointjavaxの注釈で、@Autowiredコンポーネントは、ばねブートが管理しています。これら二つは一緒に使用することはできません。これを解決するには、追加することですSpringConfiguratorのコンフィギュレータとしてServerEndpoint私はこれを試したとき、私は次のエラーを取得する実行します。

ルートWebApplicationContextを見つけることができませんでした。ContextLoaderListenerは使用されませんでしたか?

春ブートのWebSocketには例がありませんページを使用するにはContextLoaderListenerどのように使用することができるContextLoaderListenerコンポーネントを注入することができるように、@ServerEndpoint注釈付きのコントローラ?

以下は、私のコードです。

WebSocketのコントローラ

@ServerEndpoint(value = "/call-stream", configurator = SpringConfigurator.class)
public class CallStreamWebSocketController
{  
    @Autowired
    private IntelligentResponseService responseServiceFacade;

    // Other methods
}

WebSocketの構成

@Configuration
public class WebSocketConfiguration
{
    @Bean
    public CallStreamWebSocketController callStreamWebSocketController()
    {
        return new CallStreamWebSocketController();
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter()
    {
        return new ServerEndpointExporter();
    }
}

編集:これは、の重複としてタグ付けされてきたこの問題。私は答えに指定された解決策を試してみました。解決策は、追加することであるSpringConfiguratorのコンフィギュレータとして@ServerEndpointこれを追加した後、私はまだエラーが詳細に言及したのですか。

ワイン:

いくつかの研究の後、私は外部で管理/インスタンス化されたクラスにコンポーネントを注入する力スプリングブートへの道を見つけました。

1)拡張あなたのクラスにジェネリックメソッドを追加ApplicationContextAwareBeanを返すように。

@Component
public class SpringContext implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        SpringContext.context = context;
    }

    public ApplicationContext getApplicationContext() {
        return context;
    }

    // Generic method to return a beanClass
    public static <T> T getBean(Class<T> beanClass)
    {
        return context.getBean(beanClass);
    }
}

2)あなたが注入されることにしたいクラスのオブジェクトを初期化するために、このメソッドを使用します

private IntelligentResponseService responseServiceFacade = SpringContext.getBean(IntelligentResponseService.class);

したがって、上記の変更後の私のWebSocketコントローラは次のようになります。

@ServerEndpoint(value = "/call-stream", configurator = SpringConfigurator.class)
public class CallStreamWebSocketController
{  
    private IntelligentResponseService responseServiceFacade = SpringContext.getBean(IntelligentResponseService.class);

    // Other methods
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=213007&siteId=1