Bean后处理器两个方法的回调时机
先看运行结果:顺序如下
1、Chinese被实例化了
2、Spring正执行依赖注入name
3、初始化之前对Chinese加强处理
4、执行afterPropertiesSet方法
5、执行初始化方法
6、初始化之后对Chinese加强处理
7、初始化之前对Son加强处理
8、初始化之后对Son加强处理
9、新Chinese人会用斧头
由此初步总结出
1、将Bean实例化
2、注入依赖关系
3、回调postProcessBeforeInitialization进行后处理
4、调用afterPropertiesSet
5、调用init-method方法
6、回调postProcessAfterInitialization
7、执行下一个Bean
附上代码
configrelax.myBeanProcessor.java
package configrelax;
import java.lang.reflect.Field;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class myBeanProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化之后对"+beanName+"加强处理");
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化之前对"+beanName+"加强处理");
if(bean instanceof Chinese)
{
try
{
Class clazz=bean.getClass();
Field f=clazz.getDeclaredField("name");
f.setAccessible(true);
f.set(bean,"新Chinese");
}catch(Exception e)
{
e.printStackTrace();
}
}
return bean;
}
}
configrelax.Chinese.java
package configrelax;
import org.springframework.beans.factory.InitializingBean;
public class Chinese implements Person,InitializingBean {
public String name;
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("执行afterPropertiesSet方法");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
System.out.println("Spring正执行依赖注入name");
}
public Chinese()
{
System.out.println("Chinese被实例化了");
}
public void useAxe()
{
System.out.println(name+"人会用斧头");
}
public void init()
{
System.out.println("执行初始化方法");
}
}
configrelax.Person.java
package configrelax;
public interface Person
{
public void useAxe();
}
configrelax.Son.java
package configrelax;
public class Son {
public int age;
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
}
beans.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="Chinese" class="configrelax.Chinese" p:name="老Chinese" init-method="init"/>
<bean id="Son" class="configrelax.Son"/>
<bean class="configrelax.myBeanProcessor"/>
</beans>
configrelax.maintest.java
package configrelax;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class maintest {
public static void main(String[] args)
{
ApplicationContext cn=new ClassPathXmlApplicationContext("beans.xml");
Person per=cn.getBean("Chinese", Person.class);
per.useAxe();
}
}