问题场景:
笔者在springboot项目中使用java_websocket作为客户端,调用第三方ws服务。
最初只调用一个ws服务,以下代码可以正常工作:
@Bean public URI ttsUri() throws URISyntaxException { return new URI("ws://1.1.1.1:8888/xxx"); } @Slf4j @Component("ttsOfflineClient") public class OfflineTTSWsClient extends WebSocketClient { @Autowired public OfflineTTSWsClient(URI serverUri) throws IOException { super(serverUri); } ...... }
后来又加一个ws服务:ws://2.2.2.2:7777/aaaa 尝试写以下代码报错
@Bean(name = "ttsUri")
public URI ttsUri() throws URISyntaxException {
return new URI("ws://1.1.1.1:8888/xxx");
}
@Autowired @Qualifier(value = "ttsUri") public OfflineTTSWsClient(URI serverUri) throws IOException { super(serverUri); } //报错:@Qualifier is not applicable for constructor
正确方法
@Autowired public OfflineTTSWsClient(@Qualifier(value = "ttsUri") URI serverUri) throws IOException { super(serverUri); }
或者(注意两段代码差别)
public OfflineTTSWsClient(@Qualifier(value = "ttsUri") URI serverUri) throws IOException { super(serverUri); }
最终两个ws正常工作代码如下:
@Bean(name = "ttsUri") public URI ttsUri() throws URISyntaxException { return new URI(""ws://1.1.1.1:8888/xxx"); } @Bean(name = "asrUri") public URI asrUri() throws URISyntaxException { return new URI("ws://2.2.2.2:7777/aaaa"); } @Slf4j @Component("ttsOfflineClient") public class OfflineTTSWsClient extends WebSocketClient { @Autowired public OfflineTTSWsClient(@Qualifier(value = "ttsUri") URI serverUri) throws IOException { super(serverUri); } } @Slf4j @Component("asrOfflineClient") public class OfflineASRWsClient extends WebSocketClient { public OfflineASRWsClient(@Qualifier(value = "asrUri") URI serverUri) { super(serverUri); } }
参考来源:https://stackoverflow.com/questions/42350828/why-qualifier-not-allowed-above-constructor