Spring Boot Application后台守护Daemon应用

问题的提出

在系统基于Spring Boot来构建Web应用之后,其实Spring Boot对于应用的支持同样非常的好,但是在程序其中之后,则程序自动就退出了,这个是什么情况?
系统的日志如下:


2018-08-10 16:38:29.525  INFO 12068 --- [  restartedMain] org.config.test.App1Application          : Starting App1Application on ZB-PF0V10MN with PID 12068 (D:\sourcespace\app1\target\classes started by chenjunfeng1 in D:\sourcespace\app1)
2018-08-10 16:38:29.526  INFO 12068 --- [  restartedMain] org.config.test.App1Application          : No active profile set, falling back to default profiles: default
2018-08-10 16:38:29.621  INFO 12068 --- [  restartedMain] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@747d33e8: startup date [Fri Aug 10 16:38:29 CST 2018]; root of context hierarchy
2018-08-10 16:38:30.457  INFO 12068 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2018-08-10 16:38:30.478  INFO 12068 --- [  restartedMain] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-08-10 16:38:30.520  INFO 12068 --- [  restartedMain] org.config.test.App1Application          : Started App1Application in 1.987 seconds (JVM running for 4.342)
2018-08-10 16:38:30.539  INFO 12068 --- [       Thread-8] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@747d33e8: startup date [Fri Aug 10 16:38:29 CST 2018]; root of context hierarchy
2018-08-10 16:38:30.545  INFO 12068 --- [       Thread-8] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

程序在启动之后,自动退出了。

问题分析

对于应用来说,无需监听,在执行完任务之后,就自动退出,这个是非常正常的情况。那该如何做才能在后台让其一直运行呢?
办法也很简单,就是利用Thread.joni()功能来实现,让主线程等待当前线程的退出,但是当前线程一直执行下去,不退出,则可以形成一个监听状态的应用。
应用代码如下:

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyCMDLine implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        Thread.currentThread().join();
    }
}

总结

这个CommandLineRunner还可以接收来自启动命令和控制台的输入信息,并针对这些参数,将应用做出相应的调整。

猜你喜欢

转载自blog.csdn.net/blueheart20/article/details/81566000