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).生命周期图:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
您可能感兴趣的文章:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。