zoukankan      html  css  js  c++  java
  • Spring中的PropertyEditor的简单实用方法

    用于属性的转换,是BeanPostProcessor的一种,比如有如下两个java类: 
    01package com.google.spring.applicationContext;
    02 
    03public class Computer
    04{
    05    private String name;
    06     
    07    public Computer()
    08    {
    09         
    10    }
    11     
    12    public Computer(String name)
    13    {
    14        this.name = name;
    15    }
    16 
    17    public String getName()
    18    {
    19        return name;
    20    }
    21 
    22    public void setName(String name)
    23    {
    24        this.name = name;
    25    }
    26     
    27}

    01package com.google.spring.applicationContext;
    02 
    03public class Person
    04{
    05    private Computer computer ;
    06 
    07    public Computer getComputer()
    08    {
    09        return computer;
    10    }
    11 
    12    public void setComputer(Computer computer)
    13    {
    14        this.computer = computer;
    15    }
    16     
    17     
    18}

    假若在XML中进行如下配置: 
    1<bean id="person" class="com.google.spring.applicationContext.Person">
    2   <property name="computer">
    3       <value>lenovo</value>
    4   </property>
    5</bean>

    这时候在getBean("person")的时候是有问题的。通过PropertyEditor 可以将字符串映射为其它类型: 
    01package com.google.spring.applicationContext;
    02 
    03import java.beans.PropertyEditorSupport;
    04 
    05public class ComputerTypeEditor extends PropertyEditorSupport
    06{
    07    private String format;
    08 
    09    public String getFormat()
    10    {
    11        return format;
    12    }
    13 
    14    public void setFormat(String format)
    15    {
    16        this.format = format;
    17    }
    18     
    19    public void setAsText(String text)
    20    {
    21        Computer computer = new Computer(text);
    22        this.setValue(computer);
    23    }
    24}

    在XML中注册一下该转换器: 
    01<bean id="customEditorConfigure"class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    02     <property name="customEditors">
    03         <map>
    04            <entry key="com.google.spring.applicationContext.Computer">
    05               <beanclass="com.google.spring.applicationContext.ComputerTypeEditor">
    06                   <property name="format">
    07                       <value>upperCase</value>
    08                   </property>
    09               </bean>
    10            </entry>
    11         </map>
    12     </property>
    13</bean>

    这时候便可正确的注入了: 
    1Person person = (Person)applicationContext.getBean("person");
  • 相关阅读:
    C#代码常用技巧
    MVC
    json类型
    android 上传二进制文件的两种方式
    BroadcastReceiver 使用goAsync 执行异步操作
    android组件间通信又一种方式
    Android BLE基础框架使用详解
    Android BLE设备蓝牙通信框架BluetoothKit
    android studio ndk开发总结
    jni c基础总结
  • 原文地址:https://www.cnblogs.com/chenying99/p/2625903.html
Copyright © 2011-2022 走看看