springboot框架在容器加载完成之后执行某个方法
Posted 冰柠檬的夏天
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot框架在容器加载完成之后执行某个方法相关的知识,希望对你有一定的参考价值。
问题描述:
想在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(){
// 执行操作即可。
}
以上是关于springboot框架在容器加载完成之后执行某个方法的主要内容,如果未能解决你的问题,请参考以下文章