`
thaIm
  • 浏览: 91199 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Spring --- Data Binding

阅读更多
一) BeanWrapper
  BeanWrapper这个类一般不会被Spring的使用者直接调用,而是使用DataBinder和BeanFactory这两个类是间接被调用的。但是知道BeanWrapper的使用方式对于理解Spring的数据绑定机制还是十分用益的。下面我们就来看个BeanWrapper被直接调用的例子:
//首先是两个对象类Company  Employee
public class Company {
  private String name;
  private Employee managingDirector;
  public String getName() {
    return this.name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public Employee getManagingDirector() {
    return this.managingDirector;
  }
  public void setManagingDirector(Employee managingDirector) {
    this.managingDirector = managingDirector;
  }
}

public class Employee {
  private String name;
  private float salary;
  public String getName() {
    return this.name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public float getSalary() {
    return salary;
  }
  public void setSalary(float salary) {
    this.salary = salary;
  }
}

BeanWrapper company = BeanWrapperImpl(new Company());
// setting the company name..
company.setPropertyValue("name", "Some Company Inc.");
// ... can also be done like this:
PropertyValue value = new PropertyValue("name", "Some Company Inc.");
company.setPropertyValue(value);
// ok, let's create the director and tie it to the company:
BeanWrapper jim = BeanWrapperImpl(new Employee());
jim.setPropertyValue("name", "Jim Stravinsky");
company.setPropertyValue("managingDirector", jim.getWrappedInstance());
// retrieving the salary of the managingDirector through the company
Float salary = (Float) company.getPropertyValue("managingDirector.salary");

  这便是BeanWrapper的核心作用——数据绑定!

二)PropertyEditor -- 属性编辑器
  Spring的数据绑定非常强大。属性编辑器PropertyEditor的主要功能就是将外部的设置值转换为JVM内部的对应类型,所以属性编辑器其实就是一个类型转换器。它负责String与Object之间的转换。Spring本身已经定义了许多种类的属性编辑器,所以一些常用类型的转换已经不需要我们再关心了。我们关心的应该是如何自定义的PropertyEditor去满足某些特殊类的转换。
  你可以有两种方式定义PropertyEditor,但不管采用哪种Spring都使用java.beans.PropertyEditorManager类来搜寻一个类所对应的属性编辑器。
  1' 第一种当然是默认路径。

  如图,FooEditor便是Foo的属性编辑器了。在同一Package下,Spring默认类名+"Editor" 便是该类的属性编辑器。

  2'当然,第二种你也可以自定义属性编辑器的位置和名称。
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
  <property name="customEditors">
    <map>
     <entry key="example.ExoticType" value="example.ExoticTypeEditor"/>
    </map>
  </property>
</bean>

注:如果使用BeanFactory,用户需要手工调用registerCustomEditor(Class requiredType, PropertyEditor propertyEditor)方法注册自定义属性编辑器;如果使用ApplicationContext,则只需要在配置文件通过CustomEditorConfigurer注册就可以了。一般情况下,我们当然使用ApplicationContext。如上面这个例子,我们自定义了一个名叫ExoticTypeEditor的属性编辑器,它专门负责对ExoticType类的转换。具体的代码如下:
// converts string representation to ExoticType object
package example;
public class ExoticTypeEditor extends PropertyEditorSupport {
  public void setAsText(String text) {
    setValue(new ExoticType(text.toUpperCase()));
  }
}
---------------------------------------------------------------
package example;
public class ExoticType {
  private String name;
  public ExoticType(String name) {
    this.name = name;
  }
}

注:一般地,我们要使用PropertyEditor时,并不直接实现此接口,而是通过继承实现此接口的java.beans.PropertyEditorSupport来简化我们的工作,在子类覆盖setAsText方法就可以了,setValue方法一般不直接使用,在setAsText方法中将字符串进行转换并产生目标对象以后,由调setAsText调用setValue来把目标对象注入到编辑器中。当然,你可用覆盖更多的方法来满足你的特殊要求。
  这样当我们遇到如下情况时,我们的自定义属性编辑器便会被触发使用(反射机制):
public class DependsOnExoticType {
  private ExoticType type;
  public void setType(ExoticType type) {
    this.type = type;
  }
}
<bean id="sample" class="example.DependsOnExoticType">
  <property name="type" value="aNameForExoticType"/>
</bean>


  3' 刚说了只有两种定义属性编辑器的方式,这会儿咋又来第三种呢?呵呵,这种方式确实有点..."另类"?但它的作用非常大,它可以满足一个类中用到多个属性编辑器的情况:

    还是首先讲讲命名规则,如图,FooBeanInfo便是Foo类的BeanInfo了。同一Package下,类名+"BeanInfo" 便是该类对应的属性编辑器,与之前不同的是,它说明了该了中需要使用到的一个或多个子属性编辑器。而它的代码实现如下:
public class FooBeanInfo extends SimpleBeanInfo {
  public PropertyDescriptor[] getPropertyDescriptors() {
    try {
      final PropertyEditor numberPE = new CustomNumberEditor(Integer.class, true);
      PropertyDescriptor ageDescriptor = new PropertyDescriptor("age", Foo.class) {
         public PropertyEditor createPropertyEditor(Object bean) {
           return numberPE;
         };
      };
      return new PropertyDescriptor[] { ageDescriptor };
    }
    catch (IntrospectionException ex) {
      throw new Error(ex.toString());
    }
  }
}

注:BeanInfo接口有一个常用的实现类:SimpleBeanInfo,一般情况下,可以通过扩展SimpleBeanInfo实现自己的功能。

三)PropertyEditorRegistrars
  这个数据绑定接口结合Spring MVC模块一起使用效果非常好。结合一个例子就非常容易明白:
   首先是声明和配置:
package com.foo.editors.spring;
public final class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {
  public void registerCustomEditors(PropertyEditorRegistry registry) {
    // it is expected that new PropertyEditor instances are created
    registry.registerCustomEditor(ExoticType.class, new ExoticTypeEditor());
    // you could register as many custom property editors as are required here...
  }
}

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
  <property name="propertyEditorRegistrars">
  <list>
    <ref bean="customPropertyEditorRegistrar"/>
  </list>
  </property>
</bean>
<bean id="customPropertyEditorRegistrar" class="com.foo.editors.spring.CustomPropertyEditorRegistrar"/>

  而后是在Spring MVC中使用它:
public final class RegisterUserController extends SimpleFormController {
  private final PropertyEditorRegistrar customPropertyEditorRegistrar;
  public RegisterUserController(PropertyEditorRegistrar propertyEditorRegistrar) {
    this.customPropertyEditorRegistrar = propertyEditorRegistrar;
  }
  protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
    this.customPropertyEditorRegistrar.registerCustomEditors(binder);
  }
  // other methods to do with registering a User
}

  这样就实现了http请求参数与对应类的转换。而且代码还可高度重用,非常好的一个设计!
  • 大小: 7.7 KB
  • 大小: 7.3 KB
分享到:
评论

相关推荐

    spring-boot-reference.pdf

    29.3. JPA and “Spring Data” 29.3.1. Entity Classes 29.3.2. Spring Data JPA Repositories 29.3.3. Creating and Dropping JPA Databases 29.3.4. Open EntityManager in View 29.4. Using H2’s Web Console ...

    最全最经典spring-mvc教程

    另外,Spring MVC与Spring框架的其他组件无缝集成,如Spring AOP(面向切面编程)用于实现日志、事务管理等功能,Spring JDBC和MyBatis等持久层框架用于数据库操作,以及Spring Data JPA、Hibernate等ORM工具,使得...

    spring-framework-4-reference

    Validation, Data Binding, and Type Conversion部分讲解了Spring中如何进行验证、数据绑定和类型转换。Spring提供了一个Validator接口,可以用来执行验证操作,并且可以将错误代码解析为错误信息。BeanWrapper类...

    spring-framework-5.0.8.RELEASE-dist.zip

    在数据访问层,Spring Data 项目提供了一种简化数据库访问的抽象,支持多种持久化技术,如 JPA、JDBC 和 NoSQL 数据库。5.0.8.RELEASE 版本可能包含针对这些模块的改进,提高数据操作的效率和一致性。 在测试方面,...

    spring-framework-3.0.2.RELEASE-dependencies.zip

    在Spring中,Hibernate可以与Spring的Data Access/Integration模块集成,提供数据访问和事务管理。 3. **JAXB (javax.xml.stream)**:Java Architecture for XML Binding,用于将Java对象转换为XML,反之亦然。...

    Spring MVC 学习笔记 十一 data binding

    错误信息可以通过`BindingResult`对象获取。 9. **数据绑定与异常处理** 如果数据绑定过程中出现错误,Spring MVC会自动抛出异常,如`MethodArgumentNotValidException`。通过配置全局异常处理器,我们可以统一...

    Spring-MVC-step-by中文版.pdf

    介绍如何在视图中显示业务数据,并且添加消息绑定(Message Binding)机制,使得用户输入能够被正确解析和处理。 - **第18步:添加一些测试数据来自动组装一些业务对象** 为了简化开发和测试流程,可以预先定义...

    spring-gui.zip_GUI_spring

    5. **数据绑定**:Spring的Data Binding功能可能被用于连接GUI组件(如文本框)与模型数据,实现数据的自动同步。 6. **依赖注入**:Spring的核心特性之一,可以用于GUI组件的创建和管理,减少代码间的耦合。 7. *...

    spring-frame-4-reference

    #### Validation, Data Binding, and Type Conversion Spring提供了强大的验证、数据绑定和类型转换功能,这对于Web开发尤为重要。主要包括以下几个方面: - **Validation using Spring’s Validator interface**...

    Getting.started.with.Spring.Framework.2nd.Edition1491011912.epub

    Chapter 11 – Validation and data binding in Spring Web MVC Chapter 12 –Developing RESTful web services using Spring Web MVC Chapter 13 – More Spring Web MVC – internationalization, file upload and...

    Spring-Formularios_Thymeleaf-_y-_Data_Binding

    文件名列表中的"Spring-Formularios_Thymeleaf-_y-_Data_Binding-master"可能表示这是一个项目的源代码仓库,包含了相关的配置文件、Java类、Thymeleaf模板等。开发者可以研究这些文件来学习如何在实践中应用Spring ...

    apache-camel-spring-demo

    Apache Camel provides support for Bean Binding and seamless integration with popular frameworks such as CDI, Spring, Blueprint and Guice. Camel also has extensive support for unit testing your routes.

    spring-framework-reference-4.1.2

    3. New Features and Enhancements in Spring Framework 4.0 ............................................ 17 3.1. Improved Getting Started Experience .........................................................

    Spring-Rest-Jackson-Json-Data-Binding:代表性状态转移是一种软件体系结构样式,它定义了一组用于创建Web服务的约束。 符合REST架构风格的Web服务(称为Rest API)可在Internet上的计算机系统之间提供互操作性。

    Spring-Rest-Jackson-Json-数据绑定 代表性状态转移是一种软件体系结构样式,它定义了一组用于创建Web服务的约束。 符合REST架构风格的Web服务(称为Rest API)可在Internet上的计算机系统之间提供互操作性。我们在...

    Spring-Framework-4.x参考文档.pdf

    **3.3 Validation, Data Binding, and Type Conversion** - **3.3.1 验证介绍**: 介绍了 Spring 提供的验证支持。 - **3.3.2 使用 Spring 的 Validator 接口进行验证**: 详细解释了如何使用 Validator 接口进行数据...

    spring-mvc4.3.1 JAR包

    7. **Data Binding**:Spring MVC提供自动的数据绑定功能,可以将HTTP请求参数自动绑定到控制器方法的参数上,简化了数据处理。 8. **Validator**:Spring MVC提供了一种验证模型数据的方式,通过实现Validator接口...

    spring-framework-reference4.1.4

    3. New Features and Enhancements in Spring Framework 4.0 ............................................ 17 3.1. Improved Getting Started Experience .........................................................

    spring framework4

    Core technologies: dependency injection, events, resources, i18n, validation, data binding, type conversion, SpEL, AOP. Testing: mock objects, TestContext framework, Spring MVC Test, WebTestClient. ...

    cjs-springsecurity-example-master

    AngularJS is what would have been, had it been designed for building web-apps. Declarative templates with data-binding, MVC, dependency injection.

Global site tag (gtag.js) - Google Analytics