spring是借助ioc容器进行bean的初始化的,ioc的概念如下:

Spring源码之bean的生命周期

 

bean的生命周期:
           bean创建---初始化----销毁的过程
  容器管理bean的生命周期;
 我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法
  
  构造(对象创建)
          单实例:在容器启动的时候创建对象
          多实例:在每次获取的时候创建对象
 BeanPostProcessor.postProcessBeforeInitialization


 初始化:
         对象创建完成,并赋值好,调用初始化方法。。。
  BeanPostProcessor.postProcessAfterInitialization
 销毁:
         单实例:容器关闭的时候
         多实例:容器不会管理这个bean;容器不会调用销毁方法

 

Spring对外提供可使用的bean的初始化方式:

 1)、指定初始化和销毁方法;
          通过@Bean指定init-method和destroy-method;
 2)、通过让Bean实现InitializingBean(定义初始化逻辑),
                  DisposableBean(定义销毁逻辑);

package com.atguigu.bean;

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

@Component
public class Cat implements InitializingBean,DisposableBean {
	
	public Cat(){
		System.out.println("cat constructor...");
	}

	@Override
	public void destroy() throws Exception {
		// TODO Auto-generated method stub
		System.out.println("cat...destroy...");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		System.out.println("cat...afterPropertiesSet...");
	}

}


 3)、可以使用JSR250;
 4)、BeanPostProcessor【interface】:bean的后置处理器;
         在bean初始化前后进行一些处理工作;
         postProcessBeforeInitialization:在初始化之前工作
         postProcessAfterInitialization:在初始化之后工作

@ComponentScan("com.atguigu.bean")
@Configuration
public class MainConfigOfLifeCycle {
	//  多实例:容器不会管理这个bean;容器不会调用销毁方法
	@Scope("prototype")
	@Bean(initMethod="init",destroyMethod="detory")
	public Car car(){
		return new Car();
	}

}
package com.atguigu.bean;

import org.springframework.stereotype.Component;

@Component
public class Car {
	
	public Car(){
		System.out.println("car constructor...");
	}
	
	public void init(){
		System.out.println("car ... init...");
	}
	
	public void detory(){
		System.out.println("car ... detory...");
	}

}

 

package com.atguigu.test;

import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.atguigu.config.MainConfigOfLifeCycle;

public class IOCTest_LifeCycle {
	
	@Test
	public void test01(){
		//1、创建ioc容器
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
		System.out.println("容器创建完成...");
		
		//applicationContext.getBean("car");
		//关闭容器
		applicationContext.close();
	}

}

BeanPostProcessor 初始化bean的示意图: 

Spring源码之bean的生命周期

Spring底层对 BeanPostProcessor 的使用;
         bean赋值,注入其他组件,@Autowired,生命周期注解功能,@Async,xxx BeanPostProcessor

相关文章:

  • 2021-12-20
  • 2022-12-23
  • 2021-11-12
  • 2022-03-03
  • 2021-04-02
  • 2021-07-29
猜你喜欢
  • 2021-09-11
  • 2022-12-23
  • 2021-05-25
  • 2021-06-03
  • 2022-01-03
  • 2022-12-23
相关资源
相似解决方案