You're trying to implement a ConversionService
to do the conversion between Strings and User objects. However, it's Converter
implementations that do this part. What you want to do is:
- Write a Converter
- Register that converter with a ConversionService
- Make use of the ConversionService.
Your converter would be something like:
final class UserConverter implements Converter<String, User> {
...
public User convert(String username) {
return userService.find(username);
}
}
You then need to register that converter. You can either write your own ConversionServiceFactoryBean or override the default:
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="example.UserConverter"/>
</list>
</property>
</bean>
If you want to use the ConversionService explicitly, as you have, just leave it as something that can be autowired. Spring and that factorybean definition will take care of the rest.
If, however, you're already using the <mvc:annotation-driven>
tag in your context, you can use its conversion-service
attribute to reference your ConversionServiceFactoryBean. You then don't need to have InitBinder or ConversionService in your class at all: by simply having a parameter of a @RequestMapping have your target type, User, the conversion will take place without you having to intervene.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…