如何让Spring一直启动不关掉

Spring是J2EE应用程序框架,深受java程序员的欢迎,大量的项目都会引入Spring框架。如果是web项目,启动Spring之后,web容器会维持进程持续运行,Spring也就可以一直出于启动状态,但如果是普通的java应用,在启动Spring之后,随着java进程的停止,spring也会停止。那么如何让spring一直启动持续服务呢?

新建测试类

spring-beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>
public class SpringApplication {

    public static void main(String[] args) {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
        context.start();
    } 
}

右击选择"Run"运行,从控制台中打印信息可以看到,spring启动之后,进程退出的时候,spring也随之停止了。

有时候,程序作为服务端程序,也需要长时间持续提供服务的,就需要维持进程不能退出。

System.in.read()

通过这句可以让主线程处于等待读入的阻塞状态,没有读入之前,会一直持续阻塞状态,进程就不会退出。

public class SpringApplication {

    public static void main(String[] args) throws IOException {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
        context.start();
        System.in.read();
    }

}

再次运行,从控制台日志可以看出,这次程序一直运行状态,没有退出

通过wait的方式阻塞线程

public class SpringApplication {

    public static void main(String[] args) {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");
        context.start();
        synchronized (SpringApplication.class) {
            try {
                SpringApplication.class.wait();
            } catch (Throwable e) {

            }
        }
    }
}

运行结果同样可以持续不会让spring退出。

 

posted @ 2023-11-10 08:49  残城碎梦  阅读(96)  评论(0编辑  收藏  举报