Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring application doesn't quit

Tags:

java

spring

I have the following code:

public class TutorialSender {

    public static void main(String[] args) throws Exception {
        ApplicationContext context = new ClassPathXmlApplicationContext("rabbit-sender-context.xml");//loading beans
        AmqpTemplate aTemplate = (AmqpTemplate) context.getBean("tutorialTemplate");// getting a reference to the sender bean
        JSONObject obj = new JSONObject();
        obj.put("messageType", "ETL:ToFile");

        for (int i = 0; i < 100; i++) {
            aTemplate.convertAndSend("ETLQueue",obj.toString());// send
          //  aTemplate.convertAndSend("Message # " + i + " on " + new Date());// send
        }

        System.out.println("send is done");
    }

}

Then I run the app, it runs to the last line and I could see "Send is done" is printed, but the app doesn't exit. Is it because of spring prevent it to quit? how can I quit?

update: we can't use context.close() directly since there is so close() function, instead need to use the following

 ((ClassPathXmlApplicationContext) context).close();
like image 904
Daniel Wu Avatar asked Apr 18 '26 09:04

Daniel Wu


1 Answers

The Spring application context stays open, and so even though your main thread is over, other threads are still available and runnable. Close out the context with context.close() to shut things down cleanly.

Additionally, consider using Spring Boot for future programs. You'd still need to actively close the context to terminate the program automatically, but the setup is a good bit easier.

like image 150
chrylis -cautiouslyoptimistic- Avatar answered Apr 21 '26 00:04

chrylis -cautiouslyoptimistic-