Spring can use the propertyedit (Attribute Editor) to convert strings to real types. Through customeditorconfigurer, applicationcontext can easily support custom
Propertyedit.
Mytype. Java
Package com. Cao. Spring. applicationcontext;
Public class mytype {
Private string text;
Public mytype (string text ){
This. Text = text;
}
Public String gettext (){
Return this. text;
}
}
Dependsontype. Java
Package com. Cao. Spring. applicationcontext;
Public class dependsontype {
Private mytype type;
Public mytype GetType (){
Return type;
}
Public void settype (mytype type ){
This. type = type;
}
}
// Custom property editor mytypeedit. Java
Package com. Cao. Spring. applicationcontext;
Public class mytypeedit extends java. Beans. propertyeditorsupport {
// Provides a conversion policy for strings
Private string format;
Public String getformat (){
Return format;
}
Public void setformat (string format ){
This. format = format;
}
// Override the setastext method of the parent class (propertyeditorsupport.
Public void setastext (string text ){
If (format! = NULL & format. Equals ("uppercase ")){
System. Out. println ("before modification:" + text );
TEXT = text. touppercase ();
}
// Obtain the type before editing
System. Out. println ("Get the type before editing" + text. getclass (). getsimplename ());
// Package it into a real type
Mytype type = new mytype (text );
// Injection package type
Setvalue (type );
}
}
Configure bean propertyedit. xml
<Beans>
<Bean id = "mybean" class = "com. Cao. Spring. applicationcontext. dependsontype">
<! -- The actual type of type is mytype, but the actual type specified here is a normal string -->
<Property name = "type">
<Value> ABC </value>
</Property>
</Bean>
</Beans>
Configure the property editor in plugin. xml
<Bean id = "AAA" class = "org. springframework. Beans. Factory. config. customeditorconfigurer">
<Property name = "customeditors">
<Map> <! -- Key specifies the converted type -->
<Entry key = "com. Cao. Spring. applicationcontext. mytype">
<! -- The custom attribute editor is configured for the internal Bean -->
<Bean class = "com. Cao. Spring. applicationcontext. mytypeedit">
<! -- Configure the String Conversion policy -->
<Property name = "format" value = "uppercase"/>
</Bean>
</Entry>
</Map>
</Property>
</Bean>
Test class:
Public class myeditortest {
Public static void main (string [] ARGs ){
Applicationcontext CTX = new classpathxmlapplicationcontext (New String [] {"application/plugin. xml", "application/propertyedit. xml "});
Dependsontype type = (dependsontype) CTX. getbean ("mybean ");
System. Out. println (type. GetType (). getclass (). getsimplename ());
System. Out. println (type. GetType (). gettext ());
}
}
// Output result:
Before modification: ABC obtains the stringmytypeabc type before editing.