在启动应用程序的时或是调试时如果能够打印出spring管理的bean的信息,那么对于调试来说有很大的帮助,以下配置可以在spring创建一个bean之后打印出bean的消息,方便调试
public class InstantiationTracingBeanPostProcessor implements BeanPostProcessor {
// simply return the instantiated bean as-is
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean; // we could potentially return any object reference here...
}
//在创建bean后输出bean的信息
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// System.out.println("Bean '" + beanName + "' created : " + bean.toString());
if (bean instanceof ServletDispatcherResult){
ServletDispatcherResult result = (ServletDispatcherResult) bean;
}
return bean;
}
}
在配置文件中
<?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:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">
<!--
when the above bean ('messenger') is instantiated, this custom
BeanPostProcessor implementation will output the fact to the system console
-->
<bean class="test.InstantiationTracingBeanPostProcessor"/>
</beans>
每次创建bean实例结束之后都会执行继承了BeanPostProcessor 类的postProcessAfterInitialization方法,就可以打印出bean的消息