欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-02 21:37:58
1.以applocationcontext上下文单例模式装配bean为例,深入探讨bean的生命周期: (1).生命周期图: (2).具体事例: person...

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

(1).生命周期图:

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

(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).生命周期图:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。