implements BeanPostProcessor
Spring当中的后置处理器是Spring体用的一个扩展点,开发者只要去实现,Spring当中的BeanPostProcessor接口,那么就能插手SpringBean实例化的一个过程(在实例化之前和实例化之后)
首相创造一个person类
public class Person {
private Integer id;
private String sex;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person() {
}
@Override
public String toString() {
return " Person [id=" + id + ", sex=" + sex + ", name=" + name + "]";
}
}
创建后置处理器
public class AfterHandler implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
Person person=(Person) bean;
if(person.getSex().equals("男")) {
person.setName("张杰");
}else {
person.setName("谢辣");
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// 就算不使用也要放回bean
return bean;
}
}
写xml文件
<bean id="person" class="com.atguigu.ioc.life.Person" init-method="init" destroy-method="destory">
<property name="id" value="1001"></property>
<property name="sex" value="男"></property>
</bean>
//把下面的bean放在xml文档 就是对该文档的任何bean操作
<bean class="com.atguigu.ioc.life.AfterHandler">
</bean>
测试
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("life.xml");
Person person = ac.getBean("person", Person.class);
System.out.println(person);
ac.close();
}
}
就可以打印id=1001 sex=男 name=张杰