私はこのトピックに関する質問がたくさんある知っています。私は春ブーツドキュメントと、ここでのソリューションのすべてを読みました。春ブーツドキュメントによると、@ServerEndpoint
javaxの注釈で、@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)拡張あなたのクラスにジェネリックメソッドを追加ApplicationContextAware
Beanを返すように。
@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
}