一、初始化和销毁
1、项目结构如下:
2、新建ReplyService类
package hjp.spring.beanlifecycle; public class ReplyService { public void addReply() { System.out.println("add replay"); } public void myInit(){ System.out.println("init方法"); } public void myDestroy(){ System.out.println("destroy 方法"); } }
3、新建beans.xml文档,init-method指定初始化时执行方法,destroy-method指定bean销毁时执行方法
注意:销毁方法要求:(1)、必须是单例的(2)、必须关闭容器
<?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 id="replyServiceId" class="hjp.spring.beanlifecycle.ReplyService" init-method="myInit" destroy-method="myDestroy"></bean> </beans>
4、新建测试类
package hjp.spring.beanlifecycle; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestApp { @Test public void demo1(){ ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("hjp/spring/beanlifecycle/beans.xml"); ReplyService replyService = applicationContext.getBean("replyServiceId", ReplyService.class); replyService.addReply(); applicationContext.close(); } }
二、后处理bean
1、spring 后处理bean提供一种机制,可以对实例对象进行修改的机制
2、后处理bean使用
(1)、编写实现类,实现接口BeanPostProcessor
package hjp.spring.beanlifecycle; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; public class MyBeanPostProcessor implements BeanPostProcessor { /** * postProcessAfterInitialization 初始化方法(也就是示例中myInit方法)之前执行 * postProcessBeforeInitialization 初始化方法(也就是示例中myInit方法)之后执行 * bean 指spring创建的实例对象,即相当于beans中配置节点bean的属性class实例化对象 * beanName 指spring 创建实例名称,即beans中配置节点bean的属性Id;可以通过beanName对bean进行过滤处理 * 如果不进行任何操作,必须将bean进行返回,否则报空指针错误 */ @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { // TODO Auto-generated method stub System.out.println("初始化前"); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { // TODO Auto-generated method stub System.out.println("初始化后"); return bean; } }
(2)、将实现类配置到spring容器,spring容器在创建bean时,都是自动使用后处理bean
<?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 id="replyServiceId" class="hjp.spring.beanlifecycle.ReplyService" init-method="myInit" destroy-method="myDestroy"></bean> <!-- 配置后处理bean,只需配置class,spring将自动使用 --> <bean class="hjp.spring.beanlifecycle.MyBeanPostProcessor"></bean> </beans>