深入理解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).生命周期图:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Springboot 如何指定获取自己写的配置properties文件的值
这篇文章主要介绍了Springboot 如何指定获取自己写的配置properties文件的值,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-07-07
JavaScript base64 与 File 之间的互转(操作方法)
在JavaScript 中,可以使用 Blob 对象将 base64 字符串转换为 File 对象,这篇文章主要介绍了JavaScript base64 与 File之间的互转,需要的朋友可以参考下2024-05-05
Spring Data JPA使用JPQL与原生SQL进行查询的操作
这篇文章主要介绍了Spring Data JPA使用JPQL与原生SQL进行查询的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-06-06


最新评论