Saturday, March 27, 2010

Registering custom property editors with Spring MVC

Recently I've been able to concentrate much more on more normal coding tasks rather than just figuring out how to configure my application. I got to the point where I wanted to receive data entered and use that to automatically fill in property values for a business object. Fortunately Spring does have support for this. You just add a parameter of the type of your desired object and Spring will setup the properties based on their names from the encoded form values.

Spring has built-in support for conversion from Strings to a large variety of types. But if your business objects has a property of an unsupported type you need to register your own custom property editor that converts a String to that unsupported type. It took me a few tries to get it right but I seem to have gotten my custom editor set up properly now.

The mistakes I made were the following:

First I was trying to set up a CustomEditorConfigurer bean in my application context and use its customEditors property to map my class to an editor. Then I noticed that the customEditors property was deprecated in Spring 3. So I changed my setup to use a PropertyEditorRegistrar instead to register my custom property editor. This still didn't work. Then I figured out that if you just add these as beans in the application context they are probably only available for converting Strings inside that application context. If you want your property editors to be available for binding web requests to objects you need to use Spring's Controller's initBinder method to register your editor with a binder. And if you are using annotation-based controller you additionally need to use the @InitBinder annotation on that method.

No comments:

Post a Comment