本文共 3032 字,大约阅读时间需要 10 分钟。
Spring Bean的生命周期是Spring容器管理bean对象的关键环节。了解这一过程有助于更好地理解Spring的内功,提升开发效率。以下是bean在Spring容器中的生命周期详细说明。
当bean被加载到容器中时,其生命周期便开始了。这一过程分为多个关键步骤:
Bean的定义加载与实例化
容器首先会寻找bean的定义信息,并根据这些信息创建bean实例。如果bean实现了BeanNameAware接口,容器会调用setBeanName()方法,将bean的ID传递给bean。属性配置
Spring容器根据bean的定义文件或注解,利用依赖注入的方式为bean的属性进行配置。如果bean实现了BeanFactoryAware接口,容器会调用setBeanFactory()方法,将工厂本身传递给bean。Bean名称设置
如果bean实现了BeanNameAware接口,容器会调用setBeanName()方法,将bean的ID传递给bean。工厂传递
如果bean实现了BeanFactoryAware接口,容器会调用setBeanFactory()方法,将工厂本身传入。后置处理
如果bean关联了BeanPostProcessor,容器会在初始化之前调用postProcessBeforeInitialization()方法,之后在初始化完成后调用postProcessAfterInitialization()方法。初始化处理
如果bean实现了InitializingBean接口,容器会调用afterPropertiesSet()方法进行初始化操作。初始化方法调用
如果bean定义了init-method方法,容器会执行该方法。定制销毁方法
如果bean实现了DisposableBean接口或定义了destory-method,容器会在关闭容器时调用相应的方法。在实际开发中,许多步骤通常不会显式使用,尤其是依赖注入、后置处理等高级功能。但理解这些过程有助于更好地定制和优化bean的创建和销毁逻辑。
以下是与bean生命周期相关的代码示例:
public class PersonService implements BeanNameAware,BeanFactoryAware,ApplicationContextAware,InitializingBean,DisposableBean { private String name; private Integer age; public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public PersonService(String abc) { System.out.println("PersonService 函数"); } public PersonService() { System.out.println("PersonService 函数"); } public void setName(String name) { System.out.println("setName(String name) 函数"); this.name = name; } public void sayHi() { System.out.println("hi " + name); } public void setBeanName(String arg0) { System.out.println("setBeanName 被调用 值" + arg0); } public void setBeanFactory(BeanFactory arg0) throws BeansException { System.out.println("setBeanFactory " + arg0); } public void setApplicationContext(ApplicationContext arg0) throws BeansException { System.out.println("setApplicationContext" + arg0); } public void init() { System.out.println("我自己的init方法"); } @PreDestroy public void mydestory() { System.out.println("释放各种资源"); } @Override public void destroy() throws Exception { System.out.println("关闭各种资源"); }} 以下是与BeanPostProcessor相关的代码示例:
public class MyBeanPostProcessor implements BeanPostProcessor { public Object postProcessAfterInitialization(Object arg0, String arg1) throws BeansException { System.out.println("postProcessAfterInitialization 函数被调用"); return arg0; } public Object postProcessBeforeInitialization(Object arg0, String arg1) throws BeansException { System.out.println(arg0 + " 被创建的时间是" + new java.util.Date()); return arg0; }} beans.xml配置文件如下:
xiaoming
以下是应用程序启动代码:
public class App1 { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("com/hsp/beanlife/beans.xml"); PersonService ps1 = (PersonService) ac.getBean("personService"); ps1.sayHi(); }} 运行结果展示了Spring容器对bean生命周期的全程管理,包括初始化、后置处理、销毁等环节的调用。通过实际项目,可以清晰地看到Spring如何为bean的创建和销毁提供保障。
转载地址:http://dfej.baihongyu.com/