分享

Spring入门16 - BeanFactoryPostProcessor接口

 风中的眼睛_ 2013-12-20

入门 16 - BeanFactoryPostProcessor接口

 撰写Bean定义档通常使用XML来撰写,XML阶层式的组织为各种元素与属性设定来说相当的方便,然而XML文件在阅读时总是要费点心力,尤其是在文件中充满了许多定义内容时。
 对于程序来说,有一些选项在设定好后通常就不会去变更,而有一些选项可能得随时调整,这时候如果能提供一个更简洁的设定档,提供一些常用选项在其中随时更改,这样的程序在使用时会更有弹性。
 我们可以实作org.springframework.beans.factory.config.BeanFactoryPostProcessor接口来提供这个功能:

BeanFactoryPostProcessor.java

public interface BeanFactoryPostProcessor {

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}


 从BeanFactoryPostProcessor接口的名称上可以得知,实作此接口的Bean,可以在BeanFactory完成依赖注入后进行一些后继处理动作,要作什么动作取决于您,例如我们就可以在BeanFactory完成依赖注入后,根据我们提供的一个简单属性文件来设定一些经常变动的选 项。
 不过这个功能,Spring已经为我们提供了一个BeanFactoryPostProcessor的实作类别了: org.springframework.beans.factory.config.PropertyPlaceholderConfigurer。我 们来看一个Bean定义档的实际例子:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www./dtd/spring-beans.dtd">

<beans>

    <bean id="configBean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

        <property name="location">

            <value>hello.properties</value>

        </property>

    </bean>

 

    <bean id="helloBean" class="onlyfun.caterpillar.HelloBean">

        <property name="helloWord">

            <value>${helloWord}</value>

        </property>

 

        ....

    </bean>

  

     ......

 

</beans>


 假设在helloBean中有许多依赖注入的属性,这些都是比较不常变动的属性,而其中helloWord会经常变动,我们可以透过hello.properties来简单的设定:

hello.properties

helloWord=Hello!Justin!


 PropertyPlaceholderConfigurer会读取location所设定的属性文件,并将helloWord的值设定给${helloWord},从而完成依赖注入。
  另一种情况是,XML定义档中定义了一些低权限程序使用人员可以设定的选项,然而高权限的程序管理员可以透过属性文件的设定,来推翻低权限程序使用人员的设 定,以完成高权限管理的统一性,Spring也提供了这么一个BeanFactoryPostProcessor的实作类别: org.springframework.beans.factory.config.PropertyOverrideConfigurer。
 来看看Bean定义档如何设定:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www./dtd/spring-beans.dtd">

<beans>

    <bean id="configBean" class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">

        <property name="location">

            <value>hello.properties</value>

        </property>

    </bean>

 

    <bean id="helloBean" class="onlyfun.caterpillar.HelloBean">

        <property name="helloWord">

            <value>Hello!caterpillar!</value>

        </property>

 

        ....

    </bean>

 

     ....

</beans>


 在这个Bean定义档中,虽然helloBean已经设定好helloWord属性,然而高权限的管理者可以使用一个hello.properties来推翻这个设定:

hello.properties

helloBean.helloWord=Hello!Justin!


 上面指定了helloBean的属性helloWord为Hello!Justin!,根据Bean定义档与hello.properties的设定, 最后helloBean的helloWord会是Hello!Justin!而不是Hello!caterpillar!。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多