spring学习笔记_05_bean的生命周期

目录

 

11步:

1.初始化和销毁方法测试

2.BeanPostProcessor 前处理bean,后处理bean方法测试

11步:

spring学习笔记_05_bean的生命周期_第1张图片

1.初始化和销毁方法测试

public class UserServiceImpl implements UserService {

	@Override
	public void addUser() {
         System.out.println("add user");
	}
	 
	 public void myInit(){
		 System.out.println("init...");
	 }
	 public void myDestroy(){
		 System.out.println("destroy...");
	 }
}

bean的配置:

 

测试:

 @Test
	 public void demo1() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
			String xmlPath= "com/rodn/e_lifecycle/a_init_destroy/beans.xml"; 
			
//			ApplicationContext act = new ClassPathXmlApplicationContext(xmlPath); 
	    	ClassPathXmlApplicationContext act = new ClassPathXmlApplicationContext(xmlPath); 
			UserService userService = (UserService)act.getBean("userService");
			userService.addUser();
			//执行销毁  要求:1.容器必须close,销毁方法执行; 2.必须是单例的 
		 	act.getClass().getMethod("close").invoke(act);
//		1.	act.getClass().getMethod("close").invoke(act);
//	        2.	((AbstractApplicationContext)act).close();
//		3. 	act.close();
		
	 }

后台输出结果:

init...
add user
五月 30, 2019 9:16:01 上午 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@2f333739: startup date [Thu May 30 09:16:01 GMT+08:00 2019]; root of context hierarchy
destroy...

2.BeanPostProcessor 前处理bean,后处理bean方法

此测试加入了aop底层动态代理的实现

提供一个 BeanPostProcessor接口的实现类 MyBeanPostProcessor ,后边要配置到xml中

/*
 * bean的生命周期:2)前处理bean,后处理bean
 */
public class MyBeanPostProcessor implements BeanPostProcessor {

	@Override
//前处理方法
	public Object postProcessBeforeInitialization(Object arg0, String arg1) throws BeansException {
		System.out.println("before");
		return arg0;
	}
	@Override
//后处理方法
	public Object postProcessAfterInitialization(Object bean, String arg1) throws BeansException {
		System.out.println("after");
		return Proxy.newProxyInstance(
				MyBeanPostProcessor.class.getClassLoader(), 
				bean.getClass().getInterfaces(),  
				new InvocationHandler() {
					
					@Override
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					    System.out.println("开启事务");
						Object obj = method.invoke(bean, args);
						System.out.println("提交事务");
						return obj;
					};
				});
		 
	}

}

bean的配置

 
  
















 

测试:

 @Test
	 public void demo1() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
			String xmlPath= "com/rodn/d_lifecycle/b_beanPostProcessor/beans.xml"; 
	    	ClassPathXmlApplicationContext act = new ClassPathXmlApplicationContext(xmlPath); 
			UserService userService = (UserService)act.getBean("userService");
			userService.addUser();
		
	 }

结果:

before
after
开启事务
add user
提交事务

 

你可能感兴趣的:(spring学习笔记)