javascript
Spring Bean 后置处理器PostProcessor
BeanPostProcessor 接口定義回調(diào)方法,可以實(shí)現(xiàn)該方法來提供自己的實(shí)例化邏輯,依賴解析邏輯等。可以在 Spring 容器通過插入一個(gè)或多個(gè) BeanPostProcessor 的實(shí)現(xiàn)來完成實(shí)例化,配置和初始化一個(gè)bean之后實(shí)現(xiàn)一些自定義邏輯回調(diào)方法。
可以配置多個(gè) BeanPostProcessor 接口,通過設(shè)置 BeanPostProcessor 實(shí)現(xiàn)的 Ordered 接口提供的 order 屬性來控制這些 BeanPostProcessor 接口的執(zhí)行順序。
BeanPostProcessor 可以對(duì) bean(或?qū)ο?#xff09;實(shí)例進(jìn)行操作,這意味著 Spring IoC 容器實(shí)例化一個(gè) bean 實(shí)例,然后 BeanPostProcessor 接口進(jìn)行它們的工作。
ApplicationContext 會(huì)自動(dòng)檢測(cè)由 BeanPostProcessor 接口的實(shí)現(xiàn)定義的 bean,注冊(cè)這些 bean 為后置處理器,然后通過在容器中創(chuàng)建 bean,在適當(dāng)?shù)臅r(shí)候調(diào)用它。
看個(gè)非常簡(jiǎn)單的例子:在任何 bean 的初始化的之前和之后輸入該 bean 的名稱:
新建一個(gè)InitHelloWorld.java文件:
public class InitHelloWorld implements BeanPostProcessor {public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {System.out.println("BeforeInitialization : " + beanName);return bean; // you can return any other object as well}public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {System.out.println("AfterInitialization : " + beanName);return bean; // you can return any other object as well} }beans.xml:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><bean id="helloWorld" class="com.sap.HelloWorld"init-method="init" destroy-method="destroy"><property name="message" value="Hello World!"/></bean><bean class="com.sap.InitHelloWorld" /></beans>把InitHelloWorld配置到beans.xml里:
控制臺(tái)輸出:
constructor called! Before Initialization : helloWorld Bean is going through init. After Initialization : helloWorld Your Message : Hello World! Bean will destroy now.創(chuàng)建Spring IOC容器時(shí),如果檢測(cè)到PostProcessor,就調(diào)用其postProcessBeforeInitialization和postProcessAfterInitialization方法:
要獲取更多Jerry的原創(chuàng)文章,請(qǐng)關(guān)注公眾號(hào)"汪子熙":
總結(jié)
以上是生活随笔為你收集整理的Spring Bean 后置处理器PostProcessor的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring里的容器和Bean对象
- 下一篇: gradle idea java ssm