欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-02-17 14:02:09|栏目:JAVA代码|点击:

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

  

上一篇:简单讲解在Java编程中实现设计模式中的单例模式结构

栏    目:JAVA代码

下一篇:java获取中文拼音首字母工具类定义与用法实例

本文标题:深入理解Spring中bean的生命周期介绍

本文地址:http://www.codeinn.net/misctech/64495.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有