RSS
热门关键字:  java  Ajax  JSP  JSF  Struts
当前位置 : 首页>Spring>列表

Spring学习笔记

来源: 作者: 时间:2007-10-25 点击:
Spring提供了一个BeanFactoryPostProcessor接口的实现类:CustomEditorConfigurer。这个类可以实现java.beans.PropertyEditor接口的类,并将字符串值转换为指定类型的对象。
通过一个简单的例子来说明。
导入Spring所需的包:commons-logging.jar,spring.jar 。(日志包和Spring包)
包下载地址:
http://www.blogjava.net/Files/ducklyl/Spring.rar

(1)创建User 类

package com.editor;

public class User {
 private String name;
 private int number;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getNumber() {
  return number;
 }
 public void setNumber(int number) {
  this.number = number;
 }

}

(2)创建HelloBean 类

package com.editor;

public class HelloBean {
 private String helloWord;
 private User user;
 public String getHelloWord() {
  return helloWord;
 }
 public void setHelloWord(String helloWord) {
  this.helloWord = helloWord;
 }
 public User getUser() {
  return user;
 }
 public void setUser(User user) {
  this.user = user;
 }


}
(3)创建UserEditor 类

package com.editor;
import java.beans.PropertyEditorSupport;

public class UserEditor extends PropertyEditorSupport{
 public void setAsText(String text)
 {
  String[] strs=text.split(",");
  int number=Integer.parseInt(strs[1]);
  
  User user=new User();
  user.setName(strs[0]);
  user.setNumber(number);
  
  setValue(user);
 }

}


(4)在类路径下创建property-config.xml
<?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="EditorConfigBean"
  class="org.springframework.beans.factory.config.CustomEditorConfigurer">
  <property name="customEditors"><!--CustomEditorConfigurer类会加载"customEditors"属性设定的map-->
   <map>
    <entry key="com.editor.User">
     <bean id="userEditor" class="com.editor.UserEditor" />
    </entry>
   </map>
  </property>
 </bean>

 <bean id="helloBean" class="com.editor.HelloBean">
  <property name="helloWord">
   <value>Hello!</value>
  </property>
  <property name="user">
   <value>ducklyl,123456</value>
  </property>
 </bean>

</beans>
(5)创建测试类

package com.editor;

import org.springframework.context.*;
import org.springframework.context.support.*;


public class SpirngTest {
 public static void main(String[] args)
 {
  //读取配置文件

共2页: 上一页 1 [2] 下一页
最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名?
注册