1 回答
TA贡献1815条经验 获得超10个赞
经过一番研究,我找到了一种强制 spring-boot 将组件注入外部管理/实例化类的方法。
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
}
添加回答
举报