深入理解Spring中bean的生命周期介绍
更新时间:2017年03月27日 08:40:28 作者:高瑞林
本篇文章主要介绍了深入理解Spring中bean的生命周期介绍,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
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并发容器CopyOnWriteArrayList实现原理及源码分析
这篇文章主要为大家详细介绍了java并发容器CopyOnWriteArrayList实现原理及源码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-05-05
SpringBoot使用RabbitMQ延时队列(小白必备)
这篇文章主要介绍了SpringBoot使用RabbitMQ延时队列(小白必备),详细的介绍延迟队列的使用场景及其如何使用,需要的小伙伴可以一起来了解一下2019-12-12
使用springboot每日推送早安问候语到用户微信的全过程
近期网上又出现一股给女朋友做微信公众号推送的潮流,所以这篇文章主要给大家介绍了关于如何使用springboot每日推送早安问候语到用户微信的相关资料,文中通过图文以及实例代码介绍的非常详细,需要的朋友可以参考下2022-11-11


最新评论