Spring Bean包装类案例之自定义PropertyEditor

javabean:

 

package Bean.CustomerPropertyEditor;

public class Company {
    
private Person director;

    
public Person getDirector() {
        
return director;
    }


    
public void setDirector(Person director) {
        
this.director = director;
    }

}



package Bean.CustomerPropertyEditor;

public class Person {
  
private String name;
  
private int age;
  
public Person(String name,int age){
      
this.name=name;
      
this.age=age;
  }

public int getAge() {
    
return age;
}

public void setAge(int age) {
    
this.age = age;
}

public String getName() {
    
return name;
}

public void setName(String name) {
    
this.name = name;
}

}

 自定义PropertyEditor

 

package Bean.CustomerPropertyEditor;

import java.beans.PropertyEditorSupport;

public class PersonEditor extends PropertyEditorSupport {

    @Override
    
public void setAsText(String text) throws IllegalArgumentException {
        String[] temp
=text.split("-");
        String name
=temp[0];
        
int age=Integer.parseInt(temp[1]);
        Person p
=new Person(name,age);
        setValue(p);
    }


}

配置文件:

 

<?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="customEditorConfigure" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
   
<property name="customEditors">
      
<map>
         
<!-- 确定目标类 -->
         
<entry key="Bean.CustomerPropertyEditor.Person">
           
<bean class="Bean.CustomerPropertyEditor.PersonEditor"></bean>
         
</entry>
      
</map>
   
</property>
 
</bean>
 
<bean id="company" class="Bean.CustomerPropertyEditor.Company">
   
<property name="director">
      
<value>gaoxiang-26</value>
   
</property>
 
</bean>
</beans>


测试代码:

 

package Bean.CustomerPropertyEditor;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import Bean.FactoryMethods.Test;

public class test {

    
/**
     * 
@param args
     
*/

    
public static void main(String[] args) {
        String path
=new Test().getClass().getResource("/").getPath();
        String realpath
=path.substring(1, path.length());
        ApplicationContext context
=new FileSystemXmlApplicationContext(realpath+"/propertyEditor.xml");
        Company c
=(Company)context.getBean("company");
        System.out.println(c.getDirector().getName()
+"*"+c.getDirector().getAge());
    }


}

 

运行结果:

gaoxiang*26

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值