手动给spring加入监听任务
1、先写1个线程类,在springboot启动加载完,自动执行的操作放在里面
@component
public class stepexecutor implements runnable {
@override
public void run() {
startstreamtask();
}
/**
* 项目启动后打开1个页面
*/
public void startstreamtask() {
try {
runtime.getruntime().exec("cmd /c start http://localhost:8080/index");
} catch (exception ex) {
ex.printstacktrace();
}
}
}
2、写1个监听器,监听项目加载完后执行指定操作
public class applicationstartup implements applicationlistener<contextrefreshedevent> {
@override
public void onapplicationevent(contextrefreshedevent event) {
applicationcontext ac = event.getapplicationcontext();
stepexecutor stepexecutor = ac.getbean(stepexecutor .class);
thread thread = new thread(stepexecutor);
thread.start();
}
}
3、给springboot的启动类添加监听任务
@springbootapplication
public class speechapplication {
public static void main(string[] args) {
springapplication springapplication = new springapplication(speechapplication .class);
springapplication.addlisteners(new applicationstartup());
springapplication.run(args);
}
}
spring容器加载完自动监听
1、实现springboot默认的监听接口,该方法在spring容器加载完自动监听
import org.springframework.beans.factory.annotation.value;
import org.springframework.boot.commandlinerunner;
import org.springframework.stereotype.component;
/**
* 配置自动启动浏览器
*/
@component
public class mycommandrunner implements commandlinerunner {
@value("${server.port}")
private string port;
@override
public void run(string... args) {
try {
runtime.getruntime().exec("cmd /c start http://localhost:" + port + "/index");
} catch (exception ex) {
ex.printstacktrace();
}
}
}
2、正常启动
@enablewebmvc
@springbootapplication
public class photoshowapplication {
public static void main(string[] args) {
springapplication.run(photoshowapplication.class, args);
}
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论