It is very easy. You can use Converters (that work like one way PropertyEditors but are stateless).
See chapter 5.5 Spring 3 Type Conversion in Spring reference.
If such an converter is registered once, you do not need any additional information, you can simply use
@RequestMapping(value="/index.html")
public ModelAndView doIndex(@RequestParam Foo param) {
For example a simple converter that load an object by its id:
@Component
@CustomConverter //custom qualifyer
public class BUdToUserConverter implements Converter<String, User> {
@Resource
private UserDao userDao;
@Override
public User convert(String source) {
Integer id = Integer.parse(source);
return this.userDao.getByBusinessId(id);
}
}
A "helper" that registers all Beans with @CustomConverter anntoation
public class ApplicationConversionServiceFactoryBean extends FormattingConversionServiceFactoryBean {
@Resource
@CustomConverter
private List<Converter<?, ?>> customConverter;
@Override
protected void installFormatters(final FormatterRegistry registry) {
super.installFormatters(registry);
for (Converter<?, ?> converter : customConverter) {
registry.addConverter(converter);
}
}
}
How to use it
UserController {
...
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ModelAndView show(@PathVariable("id") User user) {
return new ModelAndView("users/show", "user", user);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…