bean的初始化和销毁

Posted jjyy3650

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了bean的初始化和销毁相关的知识,希望对你有一定的参考价值。

需求
1. bean需要在Spring实例化完成后,再去调用一个初始化方法来完成bean的初始化方法;
2. bean需要在Spring正常销毁之前,调用一个结束方法(销毁方法)去完成一些清理工作;


准备工作
创建接口/实现类/配置文件/测试类

1 package com.java._07_init_destory;
2 
3 public interface ISomeBean {
4     void init();
5 
6     void close();
7 }
 1 package com.java._07_init_destory;
 2 
 3 public class SomebeanImpl implements ISomeBean{
 4 
 5     @Override
 6     public void init() {
 7         System.out.println("SomebeanImpl.init()");
 8     }
 9 
10     @Override
11     public void close() {
12         System.out.println("SomebeanImpl.close()");
13     }
14 
15 }
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4     xsi:schemaLocation="http://www.springframework.org/schema/beans
5 http://www.springframework.org/schema/beans/spring-beans.xsd">
6 
7     <bean id="someBean" class="com.java._07_init_destory.SomebeanImpl"/>
8     
9 </beans>
 1 package com.java._07_init_destory;
 2 
 3 import static org.junit.Assert.*;
 4 
 5 import org.junit.Test;
 6 
 7 public class SomebeanImplTest {
 8 
 9     @Test
10     public void test() {
11         
12     }
13 
14 }

方式一:手动启动
1. 在配置文件中添加init-method属性和destroy-method属性

1 <bean id="someBean" class="com.java._07_init_destory.SomebeanImpl" init-method="init" destroy-method="close"/>

2.在测试类用AbstractApplicationContext抽象类

public class SomebeanImplTest {
    private AbstractApplicationContext ctx;

    @Test
    public void test() {
        ctx = new ClassPathXmlApplicationContext("com/java/_07_init_destory/SomeBeanImplTest.xml");
        ctx.close();
    }

}

3.如果觉得测试类的ctx.close()比较low,还可以使用另外一种方式,同样可以调用配置文件中指定的关闭bean方法

1 ctx.registerShutdownHook();

方式二:自动启动

1.配置文件不变,同手动方式一样
2.在测试类运用ApplicationContext和注解
  ps:使用@ContextConfiguration标签,一定要保证**配置文件**在同包下,并且文件名格式为测试类名-context才行,否则报错.

 1 @RunWith(SpringJUnit4ClassRunner.class)
 2 @ContextConfiguration
 3 public class SomebeanImplTest {
 4     @Autowired
 5     private ApplicationContext ctx;
 6     
 7     private ISomeBean someBean;
 8     
 9     @Test
10     public void test() {
11         someBean = ctx.getBean("someBean",ISomeBean.class);
12     }
13     
14 }

补充
如果配置文件定义bean为多例,则不会调用关闭bean方法

1 <bean id="someBean" class="com.java._07_init_destory.SomebeanImpl" init-method="init" destroy-method="close" scope="prototype"/>

 









以上是关于bean的初始化和销毁的主要内容,如果未能解决你的问题,请参考以下文章

@Bean 指定初始化和销毁方法

bean的初始化和销毁

Spring 初始化bean之前,销毁bean之前

Bean的生命周期

spring-bean初始和销毁之前之后的操作

Spring学习笔记--初始化和销毁Bean