将@Service豆注入非春季班



我有一个websocket-config:

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MessageHandler(), "/websocket")
.setAllowedOrigins("*")
.addInterceptors(new HttpSessionIdHandshakeInterceptor());;
}
}

我正面临结构危机。如您所见,MessageHandler类不是@Service类。但是,类本身需要引用@Service类。我使用以下方法从应用程序上下文中提供消息处理程序的引用:

ApplicationContext context = WebSocketService.getAppContext();
WebSocketService webSocketService= (WebSocketService) context.getBean("webSocketService");

但是,该类需要 1 个以上的引用。我可以为所有依赖项堆叠上面的代码,或者我可以将MessageHandler@Service类,并自动连接所有依赖项。

MaingMessageHandler@Service类 i 将无法将其作为参数传递到addHandler((方法中。但是我可以做:

public MessageHandler getHandler(){
ApplicationContext context = WebSocketService.getAppContext();
return (MessageHandler) context.getBean("messageHandler");
}
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(getHandler(), "/websocket")
.setAllowedOrigins("*")
.addInterceptors(new HttpSessionIdHandshakeInterceptor());;
}

这可以使我免于代码冗余。然而,我感到不确定,尽管它的良好做法。

还有其他方法可以做到这一点还是我被困住了? 感谢您的帮助!

我用来创建一个非弹簧管理的bean:

public CreateOrderCommand createOrderCommand(Integer userId, Integer productId, Integer count) {
CreateOrderCommand command = new CreateOrderCommand();
command.setProductId(productId);
command.setUserId(userId);
command.setBuyCount(count);
context.getAutowireCapableBeanFactory().autowireBean(command);
context.getAutowireCapableBeanFactory().initializeBean(command, command.getClass().getName());
return command;
}

这是受到弹簧如何自动连接测试类的启发。

最新更新