1. 程式人生 > 其它 >Spring深入淺出(三),BeanPostProcessor(Spring後置處理器)

Spring深入淺出(三),BeanPostProcessor(Spring後置處理器)

BeanPostProcessor 介面也被稱為後置處理器,通過該介面可以自定義呼叫初始化前後執行的操作方法。

postProcessBeforeInitialization 方法是在 Bean 例項化和依賴注入後,自定義初始化方法前執行的;而 postProcessAfterInitialization 方法是在自定義初始化方法後執行的。

1. 建立實體類

package com.clzhang.spring.demo;

public class HelloWorld {
    private String message;

    public void setMessage(String message) {
        
this.message = message; } public void getMessage() { System.out.println("message : " + message); } public void init() { System.out.println("呼叫XML配置檔案中指定的init方法......"); } public void destroy() throws Exception { System.out.println("呼叫XML配置檔案中指定的destroy方法......"); } }

2. 建立BeanPostProcessor介面實現類

package com.clzhang.spring.demo;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class InitHelloWorld implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws
BeansException { System.out.println("InitHelloWorld Before : " + beanName); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("InitHelloWorld After : " + beanName); return bean; } }

3. 建立主程式

package com.clzhang.spring.demo;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
    public static void main(String[] args) {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        HelloWorld objA = (HelloWorld) context.getBean("helloWorld");
        objA.setMessage("物件A");
        objA.getMessage();
        
        context.registerShutdownHook();
    }
}

4. 配置檔案

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="helloWorld" class="com.clzhang.spring.demo.HelloWorld" init-method="init" destroy-method="destroy">
        <property name="message" value="Hello World!" />
    </bean>
    
    <bean class="com.clzhang.spring.demo.InitHelloWorld" />
</beans>

5. 執行

InitHelloWorld Before : helloWorld
呼叫XML配置檔案中指定的init方法......
InitHelloWorld After : helloWorld
message : 物件A
呼叫XML配置檔案中指定的destroy方法......

本文參考:

http://c.biancheng.net/spring/bean-post-processor.html