美文网首页
spring5(5) - bean的销毁

spring5(5) - bean的销毁

作者: 小白201808 | 来源:发表于2018-09-18 18:46 被阅读25次

    一.代码演示

    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配置文件

    <?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">
    
    <!-- init-method:定义初始化方法,在构造器执行之后,立马 执行
         destroy-method:定义销毁的方法,在销毁执行调用
         注意:这些都必须是单例模式才自动会调用,而且是spring测试才允许   -->
    <bean id ="myDataSource" class = "com.keen.lifescycle.MyDataSource"
          init-method="open" destroy-method="close"  />
    </beans>
    
    

    (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的销毁

          本文链接:https://www.haomeiwen.com/subject/rusmnftx.html