liguofeng29’s blog

個人勉強用ブログだっす。

Spring4 - BeanFactoryPostProcessor

BeanFactoryPostProcessorはSpringコンテナーの生成後の後処理をサポートする。

BeanFactoryPostProcessorのIF

  • postProcessBeanFactory

サンプル

package app.beanFactoryPostFrocessor;

public class Japanese{

    private int age; // 年齢
    private String name; // 名前

    public void setAge(int age) {
        this.age = age;
    }
    public void setName(String name) {
        this.name = name;
    }

    public void info() {
        System.out.println("名前 : " + this.name);
        System.out.println("年齢 : " + this.age);
    }
}
package app.beanFactoryPostFrocessor;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    /**
    * Springコンテナーの後処理
    *
    * @param  beanFactory
    */
    public void postProcessBeanFactory(
            ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("Spring・・・" + beanFactory);
    }
}
<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    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定義 -->
    <bean id="japanese" class="app.beanFactoryPostFrocessor.Japanese"
        p:name="佐藤" p:age="20">
    </bean>

    <!-- コンテナー後処理プロセッサー登録 -->
    <bean class="app.beanFactoryPostFrocessor.MyBeanFactoryPostProcessor" />
</beans>
package app.beanFactoryPostFrocessor;

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

public class TestBeanFactoryPostProcessor {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("postBeanFactoryProcessor.xml");

        // Bean取得
        Japanese p = context.getBean("japanese", Japanese.class);
        p.info();
    }
}
Spring・・・org.springframework.beans.factory.support.DefaultListableBeanFactory@18be83e4: defining beans [japanese,app.beanFactoryPostFrocessor.MyBeanFactoryPostProcessor#0]; root of factory hierarchy
名前 : 佐藤
年齢 : 20