Java/Spring/BeanPostProcessor
Версия от 18:01, 31 мая 2010; (обсуждение)
Add BeanPostProcessor To XmlBeanFactory
File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="w" class="java.lang.String">
</bean>
<bean id="beanInitLogger" class="BeanInitializationLogger"/>
</beans>
File: Main.java
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
class Main {
public static void main(String args[]) throws Exception {
XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("context.xml"));
BeanInitializationLogger logger = new BeanInitializationLogger();
factory.addBeanPostProcessor(logger);
factory.preInstantiateSingletons();
}
}
class BeanInitializationLogger implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("Bean "" + beanName + "" initialized");
return bean;
}
}
Implements BeanPostProcessor
File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="w" class="java.lang.String">
</bean>
<bean id="beanInitLogger" class="BeanInitializationLogger"/>
</beans>
File: Main.java
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
class Main {
public static void main(String args[]) throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml");
ctx.getBean("w");
}
}
class BeanInitializationLogger implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("Bean "" + beanName + "" initialized");
return bean;
}
}