关注JEECG发展历程 关注最新动态和版本, 记录JEECG成长点滴 更新日志 - 技术支持 - 招聘英才

JEECG最新版本下载 JEECG智能开发平台 - 显著提高开发效率 常见问题 - 入门视频 - 参与开源团队

商务QQ: 69893005、3102411850 商务热线(5*8小时): 010-64808099 官方邮箱: jeecgos@163.com

查看: 8201|回复: 0

入门 16 - BeanFactoryPostProcessor接口

[复制链接]
发表于 2013-8-30 17:38:26 | 显示全部楼层 |阅读模式
入门 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.springframework.org/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.springframework.org/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!。

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表