标签:加载 data throw 启动 文件中 zha xmla equal 配置
ApplicationContext的主要实现类是ClassPathXmlApplicationContext和FileSystemXmlApplicationContext,前者默认从类路径加载配置文件,后者默认从文件系统中装载配置文件。
ApplicationContext同BeanFactory声明周期有些类似,不同的是ApplicationContext会利用java的反射机制自动识别出配置文件中定义的BeanPostProcessor、InstantiationAwareBeanPostProcessor和BeanFactoryProcesssor(),并自动注册到应用的上下文中。
ApplicationContext声明周期实例
定义一个MybeanFactoryPostProcessor
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor{
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory bf) throws BeansException {
BeanDefinition bd = bf.getBeanDefinition("animal");
bd.getPropertyValues().addPropertyValue("name", "zhangsan");
System.out.println("调用MyBeanFactoryPostProcessor.postProcessBeanFactory()!");
}
}
MyBeanPostProcessor
public class MyBeanPostProcessor implements BeanPostProcessor{
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(beanName.equals("animal")){
Animal animal = (Animal)bean;
System.out.println("调用MyBeanPostProcessor.postProcessBeforeInitialization()");
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if(beanName.equals("animal")){
Animal animal = (Animal)bean;
System.out.println("调用MyBeanPostProcessor.postProcessAfterInitialization()");
}
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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="animal" class="com.rookie.bigdata.factory.domain.Animal" destroy-method="myDestory" init-method="myInit">
<property name="name" value="哈士奇"></property>
<property name="age" value="3"></property>
</bean>
<bean id="myBeanPostProcessor" class="com.rookie.bigdata.context.MyBeanPostProcessor"/>
<bean id="myBeanFactoryPostProcessor" class="com.rookie.bigdata.context.MyBeanFactoryPostProcessor"/>
</beans>
public class ApplicationTest {
public static void main(String[] args) throws Exception{
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("context/bean.xml");
Animal animal = (Animal)applicationContext.getBean("animal");
System.out.println(animal);
// animal.destroy();
((ClassPathXmlApplicationContext) applicationContext).close();
}
}
运行上面的实例即可看到ApplicationContext的声明周期的过程。
Spring IoC容器-ApplicationContext
标签:加载 data throw 启动 文件中 zha xmla equal 配置
原文地址:https://www.cnblogs.com/haizhilangzi/p/12312013.html