欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring中bean初始化与销毁的三种方式

程序员文章站 2022-05-21 22:46:09
...

一、生命周期

  1. 定义
  2. 初始化
  3. 使用
  4. 销毁

二、初始化与销毁的三种方式

1.  实现org.springframework.beans.factory.InitializingBean接口,覆盖afterPropertiesSet方法

首先beans.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-3.0.xsd">

   <bean id="zhangSan3" class="com.kjgym.service.ZhangSan2"></bean>
</beans>

然后bean类

package com.kjgym.service;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class ZhangSan2 implements InitializingBean,DisposableBean{

	@Override
	public void destroy() throws Exception {
		System.out.println("destroy");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("afterPropertiesSet");
	}
}

测试类 

package com.kjgym.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test3 {

	public static void main(String[] args) {
		ApplicationContext ac = 
				new ClassPathXmlApplicationContext("beans.xml");
		ac.getBean("zhangSan3");
		((AbstractApplicationContext) ac).close();
		
	}
}

 2.  配置init-method与destroy-method

首先beans.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-3.0.xsd">
    
    
   <!-- 第一种初始化和销毁方法 -->
   <bean id="zhangSan2" class="com.kjgym.service.ZhangSan2" init-method="start" destroy-method="stop"></bean>
 

   
 </beans>

对应beans类

package com.kjgym.service;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class ZhangSan2 {

	public void start(){
		System.out.println("张三2来了");
	}
	public void stop(){
		System.out.println("张三2走了");
	}
}

测试类

package com.kjgym.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test3 {

	public static void main(String[] args) {
		ApplicationContext ac = 
				new ClassPathXmlApplicationContext("beans.xml");
		ac.getBean("zhangSan2");
		((AbstractApplicationContext) ac).close();
		
	}
}

第三种是直接在配置文件里写入,如下图。再写方法,与第二种差不多。

Spring中bean初始化与销毁的三种方式