spring-扩展点-BeanPostProcessor

理解spring中一个bean的初始化过程非常重要,很多基础功能的扩展,就是在bean初始化的某一步进行的。

BeanPostProcessor:功能的定位是:
1、实例化bean前,实例化,实例化后的钩子(new)
2、初始化bean前,执行设置方法,初始化bean后的钩子(init-method,destory-method,setMethod)


spring-扩展点-BeanPostProcessor_第1张图片


下面做个case:
public interface IUserService {
  public String getUsername ();
  public String getPassword();
}


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class UserServiceImpl implements IUserService,
     BeanFactoryAware,
     InitializingBean,
     DisposableBean{
	private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	public UserServiceImpl(){
		logger.info("UserServiceImpl 构造函数 ");
	}
	
	private String username;
	private String password;

	public String getUsername() {
		return username;
	}

	public String getPassword() {
		return password;
	}

	public void setUsername(String username) {
		logger.info("UserServiceImpl setUsername {}",username);
		this.username = username;
	}

	public void setPassword(String password) {
		logger.info("UserServiceImpl setPassword {}",password);
		this.password = password;
	}

	@Override
	public String toString() {
		return "UserServiceImpl [username=" + username + ", password="
				+ password + "]";
	}

	
	public void initMethod(){
		logger.info("UserServiceImpl initMethod");
	}
	
	public void destroy(){
		logger.info("UserServiceImpl destroy");
	}
	
	public void destroyMethod(){
		logger.info("UserServiceImpl destroyMethod");
	}

	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		logger.info("setBeanFactory {} {}", beanFactory);
	}

	public void afterPropertiesSet() throws Exception {
		logger.info("UserServiceImpl afterPropertiesSet");
	}
	
}


public class MyInstantiationTracingBeanPostProcessor implements	
InstantiationAwareBeanPostProcessor{
	private static final Logger logger = LoggerFactory.getLogger(MyInstantiationTracingBeanPostProcessor.class);

	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		logger.info("postProcessBeforeInitialization 初始化 {} {}", bean, beanName);
		return bean;
	}

	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		logger.info("postProcessAfterInitialization 初始化 {} {}", bean, beanName);
		return bean;
	}

	public Object postProcessBeforeInstantiation(Class<?> beanClass,
			String beanName) throws BeansException {
		logger.info("postProcessBeforeInstantiation 实例化 {} {}", beanClass,beanName);
		return null;
	}

	/**
	 * 实例化
	 */
	public boolean postProcessAfterInstantiation(Object bean, String beanName)
			throws BeansException {
		logger.info("postProcessAfterInstantiation 实例化 {} {}", bean, beanName);
		return true;
	}

	public PropertyValues postProcessPropertyValues(PropertyValues pvs,
			PropertyDescriptor[] pds, Object bean, String beanName)
			throws BeansException {
		logger.info("postProcessPropertyValues 改变   PropertyValues {} {}", pvs,bean);
		return pvs;
	}

}


测试例子:
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class TestXmlBeanFactory {
	public static void main(String[] args) {
		ConfigurableListableBeanFactory factory = new XmlBeanFactory(new ClassPathResource("spring/applicationContext.xml"));
        factory.addBeanPostProcessor(new MyInstantiationTracingBeanPostProcessor());
        IUserService userService = factory.getBean(IUserService.class);
		String password = userService.getPassword();
		factory.destroyBean("user", userService);
		
		System.out.println(password);
	}

}

或者

public class TestApplicationContext {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				"classpath:spring/applicationContext.xml");
		IUserService userService = applicationContext.getBean(IUserService.class);
		String password = userService.getPassword();
		applicationContext.destroy();
		System.out.println(password);
	}

}


输出:

c.g.MyInstantiationTracingBeanPostProcessor- postProcessBeforeInstantiation 实例化 class com.gym.UserServiceImpl user
com.gym.UserServiceImpl- UserServiceImpl 构造函数
c.g.MyInstantiationTracingBeanPostProcessor- postProcessAfterInstantiation 实例化 UserServiceImpl [username=null, password=null] user
c.g.MyInstantiationTracingBeanPostProcessor- postProcessPropertyValues 改变   PropertyValues PropertyValues: length=2; bean property 'username'; bean property 'password' UserServiceImpl [username=null, password=null]
com.gym.UserServiceImpl- UserServiceImpl setUsername xinchun.wang
com.gym.UserServiceImpl- UserServiceImpl setPassword 123456
com.gym.UserServiceImpl- setBeanFactory org.springframework.beans.factory.xml.XmlBeanFactory@3a51127a: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,user,processor]; root of factory hierarchy {}
c.g.MyInstantiationTracingBeanPostProcessor- postProcessBeforeInitialization 初始化 UserServiceImpl [username=xinchun.wang, password=123456] user
com.gym.UserServiceImpl- UserServiceImpl afterPropertiesSet
com.gym.UserServiceImpl- UserServiceImpl initMethod
c.g.MyInstantiationTracingBeanPostProcessor- postProcessAfterInitialization 初始化 UserServiceImpl [username=xinchun.wang, password=123456] user
com.gym.UserServiceImpl- UserServiceImpl destroy
com.gym.UserServiceImpl- UserServiceImpl destroyMethod

你可能感兴趣的:(spring)