About registering custom PropertyEditor in Spring
Consider the following two classes:
ExoticType:
package document.six.test;public class ExoticType {private String name;public ExoticType(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
DpendsOnExoticType:
package document.six.test;public class DependsOnExoticType {private ExoticType type;public void setType(ExoticType type) {this.type = type;}public ExoticType getType() {return type;}}
Configure Spring xml
Write another test method:
package document.six.test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringTest {public static void main(String args[]) {ApplicationContext ctx = new ClassPathXmlApplicationContext("springMVC.xml");DependsOnExoticType sample = (DependsOnExoticType) ctx.getBean("sample");System.out.println(sample.getType().getName());}}
Output result:
ANameForExoticType
Look at the xml file above. We set a String for the type attribute of DependsOnExoticType, but it is automatically converted to an ExoticType object.
The key lies in the ExoticType constructor, because it has a constructor with String parameters.
To change the default PropertyEditor, you can add a custom editor to overwrite it. An automatic detection mechanism can be used when adding: that is, certain rules must be followed.
The specific rule is: The PropertyEditor class and the standard JavaBeans are in the same package, and their PropertyEditor class name is the JavaBeans class name plus "Editor", for example:
public class ExoticTypeEditor extends PropertyEditorSupport {public void setAsText(String text) {setValue(new ExoticType(text.toUpperCase()));}}
We can see that this PropertyEditor complies with the above naming rules and is placed in the same package as ExoticType. Therefore, the following output can be obtained without additional Configuration:
ANAMEFOREXOTICTYPE
What if the above rules are not met? You can use the Bean org. springframework. beans. factory. config. medmeditorconfigurer to register
Configure the customEditors attribute for this Bean. This attribute is a Map. Inject all the PropertyEditors we need to register into this Map.