spring5(5) - bean的销毁

一.代码演示

init-method="" destroy-method=""配置

(如果不使用spring测试,就无法正常关闭spring容器destroy方法就得手动调用了)

(1)MyDataSource类

package com.keen.lifescycle;

public class MyDataSource {
    public MyDataSource() {
        System.out.println("构造对象...");
    }
    public void open() {
        System.out.println("openScource");
    }
    public void close() {
        System.out.println("closeScource");
    }
    public void doWork() {
        System.out.println("do someWork");
    }

}

(2)MyDataTest-context.xml配置文件








(3)SpringJUnit测试

@SpringJUnitConfig
public class MyDataTest {
    
    @Autowired
    private MyDataSource mydata;
    
    @Test
    void testIoc() throws Exception {
        //我们此时只关心自己的工作
        
         mydata.doWork();
    }
    
}

其他测试方式演示(了解)(手动关闭Spring容器)

(1)手动添加close()

public class LifeCycleTest {

    @Test
    void test() throws Exception {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("com/keen/lifescycle/MyDataTest-context.xml");
        MyDataSource ds = ctx.getBean("myDataSource", MyDataSource.class);
        ds.doWork();
        ctx.close();//手动添加
    }
}

(2)使用lombok的 @cleanup
(前提是加入lombok库)

public class LifeCycleTest {

    @Test
    void test() throws Exception {
        @cleanup
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("com/keen/lifescycle/MyDataTest-context.xml");
        MyDataSource ds = ctx.getBean("myDataSource", MyDataSource.class);
        ds.doWork();
        ctx.close();//手动添加
    }
}

(3)最好的方式:把spring线程作为JVM的子线程 使用 ctx.registerShutdownHook();

@Test
void test2() throws Exception {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("com/keen/lifescycle/MyDataTest-context.xml");
    MyDataSource ds = ctx.getBean("myDataSource", MyDataSource.class);
    ds.doWork();
    ctx.registerShutdownHook();
}

你可能感兴趣的:(spring5(5) - bean的销毁)