BeanPostProcessor接口有两个方法,分别在bean的实例化前后做操作。有了它,我们可以很轻松的对bean做set动作,也可以返回一个完全不相关的bean。下面我来举个返回不相关bean的例子
首先我们可以建两个实体类(com.model包下)
User类
import java.io.Serializable;@SuppressWarnings("serial")public class User implements Serializable { private static final long serialVersionUID = -2247281681931694200L; private int id; private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getId() { return id; } public void setId(int id) { this.id = id; }
Log 类
public class Log implements Serializable{ private static final long serialVersionUID = -5378869442252807770L; private int id; private String Name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return Name; } public void setName(String name) { Name = name; } }
这个是实现BeanPostProcessor接口的类(com.controller包下)
import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.BeanPostProcessor;import org.springframework.context.support.ApplicationObjectSupport;import com.model.User;//ApplicationObjectSupport是对上下文容器的管理,我们可以通过它去取bean public class BeanName extends ApplicationObjectSupport implements BeanPostProcessor { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println(bean + "对象" + beanName + "实例化后要做的操作"); return bean; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println(beanName + "对象" + bean.getClass() + "前要做的操作"); if (beanName.equals("log")) { User u; u = (User) this.getApplicationContext().getBean("user"); u.setId(3); return u; } return bean; }}
配置文件applicationContext.xml(classpath下)
测试类
import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;import com.model.User;public class Test { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println(ctx.getBean("dao").getClass().getName()); }}
运行结果
user对象class com.model.User前要做的操作
com.model.User@16dadf9对象user实例化后要做的操作log对象class com.model.Log前要做的操作com.model.User@16dadf9对象log实例化后要做的操作com.model.User
可以看出,我们已经成功的返回不相关bean对象User.
另外,我也测试过了,postProcessBeforeInitialization,postProcessAfterInitialization两个方法任写一个都可以实现对bean的更换以及操作。有兴趣的可以试一下。