spring bean生命周期 深入理解Spring中bean的生命周期介绍

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

spring bean生命周期 深入理解Spring中bean的生命周期介绍

高瑞林   2021-03-24 我要评论
想了解深入理解Spring中bean的生命周期介绍的相关内容吗,高瑞林在本文为您仔细讲解spring bean生命周期的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:spring,bean生命周期,bean的生命周期,springbean的生命周期,下面大家一起来学习吧。

1.以ApplocationContext上下文单例模式装配bean为例,深入探讨bean的生命周期:

(1).生命周期图:

(2).具体事例:

person类实现BeanNameAware,BeanFactoryAware接口

public class Person implements BeanNameAware ,BeanFactoryAware{
  
  private String name;
  
  public Person(){
    System.out.println("调用构造器为属性值初始化");
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Override
  public void setBeanName(String arg0) {
    // TODO Auto-generated method stub
    System.out.println("获取beanName id值"+" "+arg0);
    
  }

  @Override
  public void setBeanFactory(BeanFactory arg0) throws BeansException {
    // TODO Auto-generated method stub
    System.out.println("获取BeanFactory" +" "+arg0);
    
  }
}

public class MyBeanPostProcessor implements BeanPostProcessor{

  @Override
  public Object postProcessAfterInitialization(Object arg0, String arg1) throws BeansException {
    // TODO Auto-generated method stub
    System.out.println("调用postProcessAfterInitialization");
    return arg0;
  }

  @Override
  public Object postProcessBeforeInitialization(Object arg0, String arg1) throws BeansException {
    // TODO Auto-generated method stub
    System.out.println("调用postProcessBeforeInitialization");
    return arg0;
  }

}

ApplicationContext.xml配置文件:

<?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的配置文件 -->
<bean id="person" class="org.jingdong.bean.life.Person">
<property name="name" value="grl"></property>
</bean>

<bean id="myBeanPostProcessor" class="org.jingdong.bean.life.MyBeanPostProcessor"></bean>
</beans>

Main.java

public class Main {
  public static void main(String[] args) {
    // 创建IOC容器
    ApplicationContext ac = new ClassPathXmlApplicationContext("org/jingdong/bean/life/applicationContext.xml");
    //从容器中获取bean实例
    Person person = (Person) ac.getBean("person");
    //使用bean
    System.out.println(person.getName());
  }
}

2.以Spring Factory装配bean为例:

(1).生命周期图:

  

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们