User
对象;BeanPostProcessor
对刚创建好的 User 对象进行加工操作,其中 postProcessBeforeInitialization
方法的第一个参数是 User 对象,第二个参数是在配置文件中指定的 id 值;InitializingBean
的初始化操作;init-method
的初始化;BeanPostProcessor
,执行 postProcessAfterInitialization
方法。实际上在实战中,我们很少处理 Spring 的初始化操作,所以没有必要区分 Before 还是 After。只需要实现其中的一个即可,显然选 After 方法更好。
先定义一个实体类 Category
:
public class Category {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Category{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
然后注入到 Spring 容器中:
<bean class="edu.lsu.pojo.Category" id="category">
<property name="id" value="1"/>
<property name="name" value="迪丽热巴"/>
</bean>
注意此时的名字是迪丽热巴。
此时我们定义一个 BeanPostProcessor,实现他的后置处理器方法,:
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
Category category = (Category) bean;
category.setName("古力娜扎");
return category;
}
}
当我们在此时的时候,输出结果就是古力娜扎;
@Test
public void test7() {
ApplicationContext ac = new ClassPathXmlApplicationContext("/applicationContext2.xml");
Category category = ac.getBean("category", Category.class);
System.out.println("category = " + category);
}
输出:
category = Category{id=1, name='古力娜扎'}