主要是学习了解spring如何利用PropertyEditor完成conversion的。参考实现来自网络和spring reference
Spring uses the concept of PropertyEditors to effect the conversion between an Object and a String.
Spring has a number of built-in PropertyEditors to make life easy. Each of those is listed below and they are all located in the org.springframework.beans.propertyeditors package. Most,but not all (as indicated below), are registered by default by BeanWrapperImpl. Where the property editor is configurable in some fashion, you can of course still register your own variant to override the default one:
Spring uses the java.beans.PropertyEditorManager to set the search path for property editors that might be needed
Registering additional custom PropertyEditors
When setting bean properties as a string value, a Spring IoC container ultimately uses standard JavaBeans PropertyEditors to convert these Strings to the complex type of the property
引用
One quite important class in the beans package is the BeanWrapper interface and its corresponding
implementation (BeanWrapperImpl). As quoted from the Javadoc, the BeanWrapper offers
functionality to set and get property values (individually or in bulk), get property descriptors, and to query
properties to determine if they are readable or writable. Also, the BeanWrapper offers support for
nested properties, enabling the setting of properties on sub-properties to an unlimited depth. Then, the
BeanWrapper supports the ability to add standard JavaBeans PropertyChangeListeners and
VetoableChangeListeners, without the need for supporting code in the target class. Last but not
least, the BeanWrapper provides support for the setting of indexed properties. The BeanWrapper
usually isn't used by application code directly, but by the DataBinder and the BeanFactory.
The way the BeanWrapper works is partly indicated by its name: it wraps a bean to perform actions on
that bean, like setting and retrieving properties.
以下是Registered by default by BeanWrapperImpl.
ByteArrayPropertyEditor
ClassEditor
CustomBooleanEditor
CustomCollectionEditor
CustomNumberEditor
FileEditor
LocaleEditor
InputStreamEditor
PatternEditor
PropertiesEditor
StringTrimmerEditor
URLEditor
not Registered by default by BeanWrapperImpl.
CustomDateEditor
Spring对于注册自定义PropertyEditor提供了完善的支持;唯一的缺点是java.beans.PropertyEditor接口拥有许多的方法,很多方法实际上与属性类型转换没有关系。幸运的是Spring提供了PropertyEditorSupport类,你的PropertyEditors可以扩展这个类,这样你就仅仅需要实现一个方法:setAsText()。
javabean:
public class User {
private int u_id;
private String userName;
private Set<String> Favorates;
private List<String>lovers;
private Map<String, Score> score;
private Properties MOU;
private Date birthday;
private Resource pic;
public void setU_id(int u_id) {
this.u_id = u_id;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setFavorates(Set<String> favorates) {
Favorates = favorates;
}
public void setScore(Map<String, Score> score) {
this.score = score;
}
public void setMOU(Properties mou) {
MOU = mou;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public void setPic(Resource pic) {
this.pic = pic;
}
public Resource getPic() {
return pic;
}
public int getU_id() {
return u_id;
}
public String getUserName() {
return userName;
}
public Set<String> getFavorates() {
return Favorates;
}
public Map<String, Score> getScore() {
return score;
}
public Properties getMOU() {
return MOU;
}
public Date getBirthday() {
return birthday;
}
public List<String> getLovers() {
return lovers;
}
public void setLovers(List<String> lovers) {
this.lovers = lovers;
}
定义自己的editor
public class DatePropertyEditor extends PropertyEditorSupport {
private String format = "yyyy-MM-dd";
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
SimpleDateFormat df = new SimpleDateFormat(format);
try {
Date date = df.parse(text);
this.setValue(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
配置文件
<!-- 基本类型 -->
<bean class="com.spring.propertTest.User" id="user">
<property name="userName" value="fisher"></property>
<property name="u_id" value="1"></property>
<!-- list以及数组类型 -->
<property name="lovers">
<list>
<value>susan</value>
<value>Angle</value>
</list>
</property>
<!-- set集合,与list配置雷同 -->
<property name="favorates">
<set>
<value>computer</value>
<value>basketball</value>
</set>
</property>
<!-- map集合以及引用类型的注入配置 -->
<property name="score">
<map>
<entry key="电脑" value-ref="score"></entry>
</map>
</property>
<!-- properties的注入配置 -->
<property name="MOU">
<props>
<prop key="today">rain!</prop>
<prop key="tomorrow">nice weather!</prop>
</props>
</property>
<property name="birthday" value="1987-2-12"></property>
<property name="pic" value="file:////e:/J2EE技术.jpg"></property>
</bean>
<!--Score-->
<bean class="com.spring.propertTest.Score" id="score">
<property name="s_id" value="1"></property>
<property name="score" value="90"></property>
</bean>
<!-- dateEditor -->
<bean class="com.spring.propertTest.DatePropertyEditor" id="dateEditor"></bean>
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<!--customEditor是map集合类型-->
<property name="customEditors">
<map>
<!--key是代表属性类型,value这里是引用自定义的dateEditor类-->
<entry key="java.util.Date" value-ref="dateEditor">
</entry>
</map>
</property>
</bean>
引用
在上面的配置文件中你应该注意三个地方:首先是使用Map类型的customEditors属性将自定义PropertyEditors注入CustomEditorConfigurer。第二点是Map表现得每一个表现单一PropertyEditor的entry的key应该是这个PropertyEditor使用的类的限定名。最后一点是我们使用了一个匿名bean用来表示Map条目的值。没有其他的bean需要访问这个bean,所以他不需要名字,你可以将它声明在<entry>标签中。
测试
public static void main(String[] args) throws IOException {
ApplicationContext factory=new ClassPathXmlApplicationContext("beans.xml");
User user = (User) factory.getBean("user");
System.out.println(user.getBirthday());
Resource res = user.getPic();
InputStream is = res.getInputStream();
byte[] by = new byte[is.available()];
is.read(by);
OutputStream os = new FileOutputStream("e:/rbk.jpg");
os.write(by);
os.close();
}
或者可以这样写:
public static void main(String[] args) throws IOException {
ConfigurableListableBeanFactory factory = new XmlBeanFactory(new ClassPathResource("beans.xml"));
CustomEditorConfigurer configurer =(CustomEditorConfigurer)factory.getBean("customEditorConfigurer");
configurer.postProcessBeanFactory(factory);
User user = (User) factory.getBean("user");
System.out.println(user.getBirthday());
Resource res = user.getPic();
InputStream is = res.getInputStream();
byte[] by = new byte[is.available()];
is.read(by);
OutputStream os = new FileOutputStream("e:/rbk.jpg");
os.write(by);
os.close();
}
引用
CustomEditorConfigurer.postProcessBeanFactory()的调用。这是在Spring中注册自定义editor的地方。应该在访问任何需要使用自定义PropertyEditors的beans之前调用它。
还有一种自定义PropertyEditor的注册方式,如下所示:
public static void main(String[] args) throws IOException {
ConfigurableListableBeanFactory factory = new XmlBeanFactory(new ClassPathResource("beans.xml"));
factory.addPropertyEditorRegistrar(new PropertyEditorRegistrar(){
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(java.util.Date.class,new DatePropertyEditor());
}
});
User user = (User) factory.getBean("user");
System.out.println(user.getBirthday());
Resource res = user.getPic();
InputStream is = res.getInputStream();
byte[] by = new byte[is.available()];
is.read(by);
OutputStream os = new FileOutputStream("e:/rbk.jpg");
os.write(by);
os.close();
}
引用
使用自定义PropertyEditor最复杂的部分是注册过程,有两种方法可以在Spring中注册你的PropertyEditor。第一种方法调用ConfigurableBeanFactory.addPropertyEditorRegistrar()并且传递PropertyEditorRegistrar的实现,在PropertyEditorRegistrar.registerCustomEditors方法中注册PropertyEditor实现。
第二种方法是首选的。在BeanFactory配置中定义一个CustomEditorConfigurer类型的bean,在这个bean的Map类型的属性中指定editors。此外,你可以使用PropertyEditorRegistrar类型的bean的list来使用自定义PropertyEditors Map。The main benefit of using the implementation of the PropertyEditorRegistrar is the MVC framework, where you can use your PropertyEditorRegistrar bean’s registerCustomEditors in the initBinder method.
分享到:
相关推荐
- `TimestampPropertyEditor.java`: 这可能是自定义的JavaBeans PropertyEditor,用于处理Oracle的TIMESTAMP类型。因为Java的Date和Oracle的TIMESTAMP有时会有类型转换问题,所以自定义PropertyEditor可以帮助我们在...
- **定制属性编辑器**:如果需要更复杂的属性编辑,可以创建自定义的PropertyEditor。 - **设计时支持**:通过JavaBeans Architecture(如Introspector和BeanInfo)提供设计时信息,增强IDE的可视化编辑能力。 - ...
5. **定制化**:开发者可以通过提供自定义的属性编辑器(PropertyEditor)来改变Bean属性的默认编辑方式,使得在设计时可以更直观地调整Bean的配置。 JavaBeans通常与Java的Inversion of Control(IoC)容器如...
`PropertyEditor`接口是JavaBeans的核心组件之一,用于处理JavaBean的属性转换。它允许我们将字符串与其他类型的数据之间进行转换。例如,在给定的例子中,`DodeDOEditor`类扩展了`PropertyEditorSupport`,并实现...
5. **自定义转换**:如果内置的类型转换不能满足需求,可以通过实现`PropertyEditor`接口创建自定义的属性编辑器,然后通过`registerCustomEditor()`方法注册到BeanUtils中,这样在进行属性赋值时,会优先使用自定义...
3. **JavaBeans PropertyEditors**:在JavaBean中,可以通过注册PropertyEditor来实现自定义类型转换。当JavaBean属性需要设置一个与当前类型不匹配的值时,Spring框架等会自动寻找并使用合适的PropertyEditor。 4....
4. **使用JavaBeans PropertyEditors**:PropertyEditor接口是java.beans包中提供的标准接口。PropertyEditors用于转换和设置bean属性的值,特别是在将数据从一种类型转换为另一种类型时,如从用户输入的字符串转换...
在Spring框架中,属性编辑器(PropertyEditor)是一个关键组件,它负责将配置文件中非标准格式的数据转换为JavaBean的可识别类型。属性编辑器是基于JavaBeans规范的,因此理解这个概念需要先了解JavaBean和JavaBeans...
JavaBeans是Java平台上的标准组件模型,本书介绍了如何设计和实现可重用的JavaBeans组件,包括属性、方法和事件的规范,以及如何使用BeanInfo类和PropertyEditor进行属性编辑。 ### 10. Security 安全是任何企业级...
它们是JavaBeans规范的一部分,用于在Java对象和字符串之间进行数据转换。在Spring中,属性编辑器被广泛应用于IoC容器,用于处理配置文件中的属性值,将字符串形式的数据转化为相应的对象类型。在“Spring学习笔记...
4. 如果仍然没有找到,Struts2会尝试使用JavaBeans的`PropertyEditor`机制进行转换。 标签中的“源码”可能意味着博客会深入到Struts2框架的源代码中,解释类型转换器的工作原理和如何根据源代码实现自定义转换器。...
它们是JavaBeans规范的一部分,用于在Java对象和其字符串表示之间进行转换。在Spring中,我们可以通过自定义属性编辑器来处理特定类型的值,例如日期、颜色代码或其他自定义对象。这在配置bean属性或处理HTTP请求...
JavaBean是一种符合JavaBeans规范的Java类,它通常具有公共的无参数构造函数,可序列化,以及可以通过getter和setter方法访问的属性。在Java的可视化编程中,JavaBean组件可以被集成开发环境(IDE)识别并用于构建...
在Java语言中,JavaBeans提供了一个PropertyEditor接口来进行数据转换。PropertyEditor的核心功能是将一个String转换为一个Java对象。从Spring 3.0开始,Spring添加了一个通用的类型转换模块,即org.springframework...
2. `org.springframework.beans-3.0.5.RELEASE.jar`:这是Spring对JavaBeans的支持,包括了对Bean的创建、配置和管理。它提供了一套强大的API用于处理Java对象的属性,如BeanWrapper和PropertyEditor,同时实现了...
10. `java.beans`:与JavaBeans组件开发相关,提供了`BeanInfo`、`PropertyEditor`等类,使得组件具有可配置性和可序列化性。 11. `java.io`:提供了输入输出流相关的类,如`FileInputStream`、`OutputStreamWriter...
- 介绍一些辅助类,如`PropertyEditor`,用于处理复杂的属性值。 - **6.5 带包名的beans** - 使用带有包名的beans,便于组织和管理。 - **6.6 JSP与beans结合的简单例子** - **6.6.1 三角形beans**:实现计算...