MicroFish

Open & Open hits
随笔 - 33, 文章 - 2, 评论 - 4, 引用 - 0
数据加载中……

《Pro Spring》学习笔记(8)--基础进阶(3)

 

      如果bean无法简单地通过new关键字来创建怎么办,通常碰到这样的情况时,我们都会使用工厂模式来处理,Spring也提供了对FactoryBean的支持,当我们配置了一个bean为FactoryBean时,随后我们获取的则并不是该FactoryBean,Spring会通过调用FactoryBean.getObject()方法,返回真正的目标bean。FactoryBean在Spring中的最著名应用就是对声明式事务的处理。
      在Spring中使用FactoryBean,我们需要编写一个实现了FactoryBean接口的类,以一个信息摘要FactoryBean为例,它主要实现根据不同的参数,创建不同的MessageDigest的实例。
public class MessageDigestFactoryBean implements FactoryBean, InitializingBean {
    private String algorithmName = "MD5";
    private MessageDigest messageDigest = null;
    public Object getObject() throws Exception {
        return messageDigest.clone();
    }
    public Class getObjectType() {
        return MessageDigest.class;
    }
    public boolean isSingleton() {
        return true;
    }
    public void afterPropertiesSet() throws Exception {
        messageDigest = MessageDigest.getInstance(algorithmName);
    }
    public void setAlgorithmName(String algorithmName) {
        this.algorithmName = algorithmName;
    }
}
      getObject方法是供Spring调用,用来返回真正的bean给其它bean的(而不是FactoryBean本身),getObjectType方法可以返回null,但如果指定了类型,就可以使用Spring的自动装载功能了。isSingleton方法是指定bean是否是单例的,注意不能通过FactoryBean的配置文件来指定bean是否为单例,因为那样指定的是FactoryBean本身,而不是真正的目标bean。
      FactoryBean的配置和普通bean并没有什么区别。
      由于Bean配置文件中,各个属性都是以String的形式配置的(除了使用ref引用其它bean外),因此,Spring在组装bean的时候,需要把String类型的值转化成合适的类型,这就需要用到JavaBean中的概念:PropertyEditor
      Spring内置了7种预先注册的PropertyEditor:ByteArrayPropertyEditor,ClassEditor,FileEditor,LocaleEditor,PropertiesEditor,StringArrayPropertyEditor,URLEditor。通过名字,我们就能清楚地知道它们对应的类型了。
      尽管内置的PropertyEditor可以处理大部分常见的类型,我们仍然会碰到需要创建自己的PropertyEditor的情况。为了简化自定义PropertyEditor的创建,Spring提供了PropertyEditorSupport类,我们只需要扩展该类,并实现其中的setAsText方法即可。
public class PatternPropertyEditor extends PropertyEditorSupport {
    public void setAsText(String text) throws IllegalArgumentException {
        Pattern pattern = Pattern.compile(text);
        setValue(pattern);
    }
}
      可以看到,实现一个自定义的PropertyEditor是很容易的,但怎么才能让它起作用呢,也就是通常所说的注册PropertyEditor。Spring提供了两种注册的方式:1.通过ConfigurableBeanFactory的registerCustomEditor方法;2.在BeanFactory的配置文件中定义CustomEditorConfigurer。
<bean name="customEditorConfigurer"
class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="customEditors">
        <map>
            <entry key="java.util.regex.Pattern">
                <bean class="com.apress.prospring.ch5.pe.PatternPropertyEditor"/>
            </entry>
        </map>
    </property>
</bean>
      自定义的PropertyEditor是通过CustomEditorConfigurer的一个类型为Map的属性添加的,key值是自定义PropertyEditor对应的类型的全类名。
      在使用时需要先调用:
CustomEditorConfigurer config =
    (CustomEditorConfigurer) factory.getBean("customEditorConfigurer");
config.postProcessBeanFactory(factory);
      来将所有自定义的ProperyEditor注册到BeanFactory中。

posted on 2006-12-21 10:24 刘璐 阅读(335) 评论(0)  编辑  收藏 所属分类: spring


只有注册用户登录后才能发表评论。


网站导航: