問題描述:
想在websocket實現的Handler中執行一些初始化操作,但是初始化操作使用到了@Autowired自動注入的變量,而且是保護類型。第一個想法是放到Handler構造函數中執行,但是@Autowired注入的變量為null,故此方法不可行。
問題解決
解決方法一
在Application啟動類中實現ApplicationListener
代碼如下
/*
* Copyright 2018 Kurento (https://www.kurento.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kurento.tutorial.rtpreceiver;
import org.kurento.client.KurentoClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;
/**
* Kurento Java Tutorial - Main Application class.
*/
@SpringBootApplication
@EnableWebSocket
@Configuration
public class Application implements WebSocketConfigurer
{ //, ApplicationListener<ApplicationReadyEvent>
@Bean
public Handler handler()
{
return new Handler();
}
@Bean
public KurentoClient kurentoClient()
{
return KurentoClient.create();
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry)
{
String[] allowsOrigins = {"*"};
registry.addHandler(handler(), "/rtpreceiver").setAllowedOrigins(allowsOrigins);
//registry.addHandler(handler(), "/rtpreceiver");
}
public static void main(String[] args) throws Exception
{
SpringApplication.run(Application.class, args);
}
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
try {
System.out.println("all is ok");
// 在此處調用其他類中需要執行的方法
} catch (Exception e) {
System.out.println("[項目啟動時調用g1] 發生錯誤,");
}
}
}
// 問是,我的Handler也是@Bean形式注入,不知道怎么調用Handler類中的方法……
解決方法二
直接在Handler類中利用@PostConstruct注解方式,PostConstruct注釋用於在依賴關系注入完成之后需要執行的方法上,以執行任何初始化。
@PostConstruct
private void pushflow(){
// 執行操作即可。
}
