user1028741
user1028741

Reputation: 2825

How can I make a spring context stay alive

I have a spring context which I run like this:

public static void main(String[] args) {

    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
            new String[]{"classpath*:db-utils.appcontext.xml"});

    ctx.registerShutdownHook();
}

where the db-utils.appcontext.xml looks like this:

<?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">

    <bean id="jmxDbUpdateUtils" class="maintain.dbutils.JmxDbUpdateUtils" >
        <property name="genericDao" ref="genericDao" />
    </bean>
    ....
</beans>

The class JmxDbUpdateUtils has a JMX method which I'd like to execute any time I like.

But, when I execute my main method - The context opens and immediately closes.

Do I have a way to keep it alive until I manually close it?

Upvotes: 1

Views: 589

Answers (1)

Atefeh
Atefeh

Reputation: 122

You must define your class so that the main thread dose not terminate until you force it. This code could help you to achieve this requirement:

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Primary {
    // public static ClassPathXmlApplicationContext ctx = new
    // ClassPathXmlApplicationContext(
    // new String[] { "classpath*:db-utils.appcontext.xml" });
    public static int i = 1;

    public static void main(String[] args) throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }
}

This class simply creates a context and lives for Long.MAX_VALUE milliseconds (292471208 years). Secondary class use Primary class data.

public class Secondary {
    public static void main(String[] args){
         System.out.println(Main.i);
        }
}

While the thread of Primary class is not dead, Secondary class could successfully use it.

Upvotes: 2

Related Questions