netty-websocket-spring-boot-starter icon indicating copy to clipboard operation
netty-websocket-spring-boot-starter copied to clipboard

使用@ServerEndpoint修饰但不用@Component时,其它Bean注入该Bean时会报 bean could not be found 异常

Open niezhiliang opened this issue 1 year ago • 2 comments

image image image 我看了源码,ServerEndpointExporter 实现自SmartInitializingSingleton这个后置处理器,该处理器是在所有的Bean都初始化完成后,再执行的,如果不用@Component修饰,只要其它Bean注入都会报这个异常。

如果搭配@Component一起使用,就不会有该问题,我看大佬本身想剔除对@Component的依赖,只需要单独使用@ServerEndpoint注解。所以提了该issue。

niezhiliang avatar Jun 27 '23 06:06 niezhiliang

我尝试的改了一下这个问题,ServerEndpointExporter 再实现一个后置处理器接口 BeanDefinitionRegistryPostProcessor,registerEndpoints中的scanPackage方法放到postProcessBeanFactory方法中执行,让扫描提前执行,就不会再报异常 `public class ServerEndpointExporter extends ApplicationObjectSupport implements SmartInitializingSingleton, BeanFactoryAware, ResourceLoaderAware,BeanDefinitionRegistryPostProcessor {

@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {

}

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
    ApplicationContext context = getApplicationContext();
    scanPackage(context);
}

protected void registerEndpoints() {
    ApplicationContext context = getApplicationContext();
    // scanPackage(context);

    String[] endpointBeanNames = context.getBeanNamesForAnnotation(ServerEndpoint.class);
    Set<Class<?>> endpointClasses = new LinkedHashSet<>();
    for (String beanName : endpointBeanNames) {
        endpointClasses.add(context.getType(beanName));
    }

    for (Class<?> endpointClass : endpointClasses) {
        if (ClassUtils.isCglibProxyClass(endpointClass)) {
            registerEndpoint(endpointClass.getSuperclass());
        } else {
            registerEndpoint(endpointClass);
        }
    }

    init();
}

}`

niezhiliang avatar Jun 27 '23 06:06 niezhiliang

我怎么感觉你的用法跟我的相反了,不是应该是MyWebSocket注入其他bean吗

liliexuan avatar Jan 09 '24 09:01 liliexuan