How does Lifecycle interface work in Spring? What are “top-level singleton beans”?

前端 未结 5 1603
無奈伤痛
無奈伤痛 2021-02-07 05:13

It is said in Spring javadoc, that \"Note that the Lifecycle interface is only supported on top-level singleton beans.\" Here URL

My LifecycleBeanTest.xml d

5条回答
  •  独厮守ぢ
    2021-02-07 06:00

    So, finally I foundm that if I:

    1) Define my bean as implements Lifecycle

    2) Introduce a delay in stop() method like this

    @Override
    public void stop() {
        log.info("Stopping bean");
        //thread.interrupt();
        try {
            thread.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return;
        }
    }
    

    3) And code context creation as follows:

    new ClassPathXmlApplicationContext("/tests/LifecycleBeanTest.xml").stop();
    

    Then I get what I want:

    context creation code does not exit until all stops of all Lifecycle beans executed. So, this code works in JUnit tests

提交回复
热议问题