码迷,mamicode.com
首页 > 其他好文 > 详细

bean的初始化和销毁

时间:2018-10-05 18:53:40      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:void   instance   实现类   添加   schema   www   method   odi   运用   

需求
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的初始化和销毁

标签:void   instance   实现类   添加   schema   www   method   odi   运用   

原文地址:https://www.cnblogs.com/jjyy3650/p/9745196.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!