spring 框架说明文档学习记录(3.6)

时间:2021-09-23 17:51:56

容器扩展

一般的,应用开发者不需要继承实现ApplicationContext。与之相对的,Spring IOC容器能够通过引入特别集成接口来扩展。

使用BeanPostProcessor定制bean

我们可以通过实现BeanPostProcessor接口定义的回调函数来实现自己的实例化逻辑、依赖解决逻辑等等。如果你想在Spring容器完成实例化、配置或初始化bean后实现一些逻辑,你可以引入一个或多个BeanPostProcessor实现。

你可以配置多个BeanPostProcessor实例,并通过设置order属性来控制BeanPostProcessor的执行顺序。仅在BeanPostProcessor实现Ordered接口时才可设置该属性,如果你编写自己的BeanPostProcessor,你也应该考虑继承Ordered接口。

简单示例

package scripting;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.BeansException;
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...
}
public Object postProcessAfterInitialization(Object bean,
String beanName) throws BeansException {
System.out.println("Bean '" + beanName + "' created : " + bean.toString());
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.xsd        http://www.springframework.org/schema/lang        http://www.springframework.org/schema/lang/spring-lang.xsd">  <lang:groovy id="messenger"        script-source="classpath:org/springframework/scripting/groovy/Messenger.groovy">    <lang:property name="message" value="Fiona Apple Is Just So Dreamy."/>  </lang:groovy>  <!--  when the above bean (messenger) is instantiated, this custom  BeanPostProcessor implementation will output the fact to the system console  -->  <bean class="scripting.InstantiationTracingBeanPostProcessor"/></beans>
BeanFactoryPostProcessor
PropertyPlaceholderConfigurer

PropertyOverrideConfigurer

FactoryBean