Spring BeanPostProcessor

Bean的属性被初始化之后,我们可以通过其他方式对Bean进行一些修改,这时就使用到了BeanPostProcessor接口。

public interface BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException;
    public Object postProcessAfterInitialization(Object bean, String name) throws BeansException;
}

BeanPostProcessor接口中提供了两个方法如下:
postProcessBeforeInitialization(前置处理):该方法会在Bean初始化之前执行
postProcessAfterInitialization(后置处理):该方法会在Bean初始化之后执行

编写一个示例:

实体类:

package pojo;

public class Person {
	private String name ;
	private String age ;
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Person(String name, String age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	} 
}

实现了BeanPostProcessor接口的类

package service;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import pojo.Person;

public class BeanPostProcessorExampleTest implements BeanPostProcessor {
	
	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		// TODO Auto-generated method stub
		System.out.println("bean初始化完成之后!");
		System.out.println(beanName + ":" +bean.toString());
		return bean;
	}

	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		// TODO Auto-generated method stub
		System.out.println("bean初始化之之前!");
		System.out.println(beanName + ":" +bean.toString());
		return new Person();
	}
}

测试类:

package main;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import pojo.Person;

public class TestMain {

	public static void main(String[] args) {
		
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml") ; 
		 
		Person p = (Person)context.getBean("person") ; 
		
		System.out.println("主方法中的person对象 : " + p.toString());
	}
}

配置文件:

<?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-3.1.xsd">

	<bean class="service.BeanPostProcessorExampleTest"/>
	
	<bean name="person" class="pojo.Person">
		<property name="name" value="张三"></property>
		<property name="age" value="18"></property>
	</bean>

</beans>
上一篇:spring bean的生命周期


下一篇:Spring中的BeanPostProcessor和BeanFactoryPostProcessor