Spring中Bean的生命周期

本文介绍如何在Spring框架中通过配置初始化和销毁方法管理Bean的生命周期,并利用BeanPostProcessor实现更细粒度的控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.初始化和销毁

目标方法执行前和执行后

配置

<?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">

<!-- bean definitions here -->
<bean id="User" class="cn.qyc.beansmzq.UserService" init-method="myInit" destroy-method="mydestroy"></bean>
</beans>

bean

package cn.qyc.beansmzq;

public class UserService implements UserServicefactory{

	public void addUser() {
		// TODO Auto-generated method stub
		System.out.println("调用UserService的addUser方法");
	}
	public void myInit() {
		System.out.println("初始化方法");
	}
	public void mydestroy() {
		System.out.println("销毁方法");
	}

}

test

package cn.qyc.beansmzq;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test01 {
	@Test
	public void demo(){
		String xmlpath = "Bean.xml";
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlpath);
		UserService userService = applicationContext.getBean("User",UserService.class);
		userService.addUser();
		applicationContext.close();
	}
}

七月 23, 2019 7:15:37 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@29444d75: startup date [Tue Jul 23 19:15:37 CST 2019]; root of context hierarchy
七月 23, 2019 7:15:37 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [Bean.xml]
七月 23, 2019 7:15:37 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4566e5bd: defining beans [User]; root of factory hierarchy
初始化方法
调用UserService的addUser方法

七月 23, 2019 7:15:37 下午 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@29444d75: startup date [Tue Jul 23 19:15:37 CST 2019]; root of context hierarchy
七月 23, 2019 7:15:37 下午 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4566e5bd: defining beans [User]; root of factory hierarchy
销毁方法

2.BeanPostProcessor后处理Bean 

  • spring提供一种机制,只要实现此接口BeanPostProcessor,并将实现类提供给spring容器,spring容器将自动执行,在初始化方法前执行before(),在初始化之后执行after()   
  • 实现:直接配置xml 中 bean的class就可以
  • 后处理bean作用于所有目标类(可以通过参数2  beanName进行控制,使作用于一个)
A a =new A();

a = B.before(a) --> 将a的实例对象传递给后处理bean,可以生成代理对象并返回。

a.init();

a = B.after(a);

a.addUser(); //生成代理对象,目的在目标方法前后执行(例如:开启事务、提交事务)

a.destroy()

配置文件 

<bean id="user" class="cn.qyc.beansmzq.UserService" init-method="myInit" destroy-method="mydestroy"></bean>
<bean class="cn.qyc.beansmzq.MyBeanPostProcessor"></bean>

接口

package cn.qyc.beansmzq;

public interface UserServicefactory {
	public void addUser();
	public void myInit();
	public void mydestroy();
}

实现接口

package cn.qyc.beansmzq;

public class UserService implements UserServicefactory{

	public void addUser() {
		// TODO Auto-generated method stub
		System.out.println("调用UserService的addUser方法");
	}
	public void myInit() {
		System.out.println("初始化方法");
	}
	public void mydestroy() {
		System.out.println("销毁方法");
	}

}

MyBeanPostProcessor

package cn.qyc.beansmzq;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;



public class MyBeanPostProcessor implements BeanPostProcessor{

	public Object postProcessBeforeInitialization(Object bean, String beanname) throws BeansException {
		// TODO Auto-generated method stub
		System.out.println("调用after()" +beanname);
		return bean;
	}

	public Object postProcessAfterInitialization(final Object bean, String beanname) throws BeansException {
		// TODO Auto-generated method stub
		System.out.println("调用before()"+beanname);
		return Proxy.newProxyInstance(
				MyBeanPostProcessor.class.getClassLoader(),
				bean.getClass().getInterfaces(),
				new InvocationHandler() {
			
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				// TODO Auto-generated method stub
				System.out.println("开启事务");
				Object object = method.invoke(bean, args);
				System.out.println("提交事务");
				return object;
			}
		});
//		return bean;
	}

}

test(注意类型为接口类型)

package cn.qyc.beansmzq;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test01 {
	@Test
	public void demo(){
		String xmlpath = "Bean.xml";
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlpath);
		UserServicefactory userService = (UserServicefactory) applicationContext.getBean("user");
		userService.addUser();
		applicationContext.close();
	}
}

七月 23, 2019 8:42:02 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@29444d75: startup date [Tue Jul 23 20:42:02 CST 2019]; root of context hierarchy
七月 23, 2019 8:42:02 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [Bean.xml]
七月 23, 2019 8:42:02 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@ff5b51f: defining beans [user,cn.qyc.beansmzq.MyBeanPostProcessor#0]; root of factory hierarchy
调用after()user
初始化方法
调用before()user
开启事务
调用UserService的addUser方法
提交事务

七月 23, 2019 8:42:02 下午 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@29444d75: startup date [Tue Jul 23 20:42:02 CST 2019]; root of context hierarchy
七月 23, 2019 8:42:02 下午 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@ff5b51f: defining beans [user,cn.qyc.beansmzq.MyBeanPostProcessor#0]; root of factory hierarchy
销毁方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值