上一篇说过相关配置的加载,下面开始将bean在spring中的生命周期,本章将先简单的执行代码查看bean的创建过程。
下面是图示:
代码演示:
①配置文件
在这段配置中使用到了set方法 initMethod 和 destroyMethod 创建UserBean
自定义 实现 BeanPostProcessor
<bean name="customBeanPostProcessor" class="com.gl.pojo.CustomBeanPostProcessor"/>
<bean name="user" class="com.gl.pojo.User" init-method="initMethod" destroy-method="destroyMethod" >
<property name="name" value="小明"/>
</bean>
②user类
user 实现 InitializingBean DisposableBean 和自定义 initMethod、destroyMethod
public class User implements InitializingBean, DisposableBean {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("执行setName");
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("执行InitializingBean");
}
@Override
public void destroy() throws Exception {
System.out.println("执行DisposableBean");
}
public void initMethod(){
System.out.println("执行initMethod");
}
public void destroyMethod(){
System.out.println("执行destroyMethod");
}
}
③实现BeanPostProcessor
public class CustomBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("执行postProcessBeforeInitialization");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("执行postProcessAfterInitialization");
return bean;
}
}
④执行获取bean
public class Test {
public static void main(String[] args) {
AbstractApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml");
User user = (User)applicationContext.getBean("user");
System.out.println(user);
applicationContext.close();
}
⑤执行结果
执行setName
执行postProcessBeforeInitialization
执行InitializingBean
执行initMethod
执行postProcessAfterInitialization
com.gl.pojo.User@6aa8ceb6
执行DisposableBean
执行destroyMethod
由此代码演示可以看到bean的生命周期的顺序,后续从源码来看bean如何创建的。
标签:04,浅入,spring,System,bean,println,执行,public,out
From: https://blog.csdn.net/qq_35175478/article/details/137038657