简体   繁体   English

将@Service bean注入非spring类

[英]Injecting @Service bean into non spring class

I have a websocket-config: 我有一个websocket-config:

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

And i am facing structure crysis. 我正面临结构孤岛危机。 As you can see, MessageHandler class is not @Service class. 如您所见, MessageHandler类不是@Service类。 However the class itself needs reference to @Service classes. 但是,该类本身需要引用@Service类。 I provide the refference for MessageHandler from application context using: 我使用以下内容从应用程序上下文中提供对MessageHandler的引用:

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

However, the class needs more than 1 refference. 但是,该类需要1个以上的引用。 I could just stack code above for all dependencies, or i could make MessageHandler @Service class, and autowire all dependencies. 我可以在上面堆叠所有依赖关系的代码,或者可以使MessageHandler @Service类成为可能,并自动装配所有依赖关系。

Maing MessageHandler @Service class i will be unable to pass it as argument into addHandler() method. Maing MessageHandler @Service类将无法将其作为参数传递给addHandler ()方法。 However i could do: 但是我可以做到:

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());;
}

Which could save my from redundancy of code. 这可以节省我的代码冗余。 However i feel unsure, whetever its good practice. 但是我不确定它的良好实践。

Is there any other way how to do this or am i stuck with this? 还有什么其他方法可以做到这一点,或者我会坚持吗? Thanks for help! 感谢帮助!

I'm used to create a non-spring-managed bean: 我习惯于创建一个非弹簧管理的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;
}

This is inspired by how spring to autowire a test class. 这是受春天如何自动连接测试班的启发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM