스프링 springboot 웹 소켓 기록 방법은 문제를 해결하기 위해 (@Autowired)를 주입 할 수 없다

특이한 채팅 메시지를 보낼 때 웹 소켓 @Service 어노테이션을 사용하는 경우 서비스 클래스가 문제를 시작하지 : java.lang.NullPointException는, 프로세스 솔루션을 많이 찾을 수 있지만, 이러한 방법은 해결되지 않습니다, 다른가있을 것입니다 약간의 오류가 발생합니다.
마지막으로 해결, Citie 나중에 검사 기록했다.

실시 예 1 : 구성자 = SpringConfigurator.class 추가 주석 이후 @ServerEndpoint

으로는 다음과

@ServerEndpoint(value = "/websocket/{user}", configurator = SpringConfigurator.class)
@Controller

문자 그대로의 의미는 ContextLoaderListener에 실행되지 않습니다에서 다음 오류가 이런 방식으로 발생합니다.

java.lang.IllegalStateException: Failed to find the root WebApplicationContext. Was ContextLoaderListener not used?

의 ContextLoaderListener는 다른 방법으로 더 깊이가없는, 보이지 않는 봄 부팅 관계, 스프링 MVC의 web.xml 구성 파일입니다.

두 번째 방법 : websock의 구성 websock 클래스 구성 클래스

으로는 다음과 같습니다 :

@Configuration
public class EndpointConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        ServerEndpointExporter serverEndpointExporter = new ServerEndpointExporter();
        serverEndpointExporter.setAnnotatedEndpointClasses(WebsocketController.class);
        return serverEndpointExporter;
    }
}

WebsocketController 웹 소켓 구현 클래스는 여전히 해결되지 않은 것입니다.

세 번째 방법 : 클래스 재 작성 ApplicationContextAware

으로는 다음과 같습니다 :

@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringUtil .applicationContext == null) {
            SpringUtil .applicationContext = applicationContext;
        }
    }
    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    public static Object getBean(String beanName){
        return applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> clazz){
        return (T)applicationContext.getBean(clazz);
    }

}

그런 다음, 서비스 방법을 구하는의 getBean

private static WeChatService weChatService = SpringUtil .getBean(WeChatService.class);

이 방법은 매우 가능 아, 시작, 오류가 보인다 ...

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'websocketController' defined in file

생성이 실패 콩이 문제를 극복하기 위해 준비하고, 실수로 우리는 다른 해결책을 찾아 냈다.

네 번째 방법 : 서비스 클래스의 초기화는 다음 @Autowired에 의해 할당

으로는 다음과 같습니다 :

	private static WeChatService weChatService ;

	@Autowired
	public void setWeChatService(WeChatService weChatService){
		this.weChatService = weChatService;
	}

지금까지 문제는 해결된다.

그러나 가능하지 않을 수 있습니다 결국 세 번째 방법은, 메시지는 큰 형제되어야합니다! ! !

종료!

게시 24 개 원래 기사 · 원의 찬양 (11) · 전망 5422

추천

출처blog.csdn.net/weixin_44037376/article/details/97644830