您可以使用Spring Formatter将 T 类型的对象格式化为 String ,反之亦然。
package org.springframework.format;
public interface Formatter<T> extends Printer<T>, Parser<T> {
}
使用此接口,您可以实现与 Barry Pitman 所说的相同,但代码更少,如果您想格式化为字符串,这是 Spring 文档的首选方式,反之亦然。所以 Barry 的 UserIdConverter 类看起来像这样:
public class UserIdConverter implements Formatter<User> {
private final UserDao userDao;
@Autowired
public UserIdConverter(UserDao userDao) {
this.userDao = userDao;
}
@Override
public User parse(String userId, Locale locale) {
return userDao.load(userId);
}
@Override
public String print(User target, Locale locale) {
return target.getUserId();
}
}
要注册此格式化程序,您应该将其包含在您的 XML 配置中:
...
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" >
<property name="formatters">
<set>
<bean class="com.x.UserIdConverter"/>
</set>
</property>
</bean>
...
!请注意,此类只能用于从某种类型 T 格式化为 String ,反之亦然。例如,您不能从类型 T 格式化为其他类型 T1。如果你有这种情况,你应该使用 Spring GenericConverter 并使用 Barry Pitman 的答案:
public abstract class AbstractTwoWayConverter<S, T> implements GenericConverter {
private Class<S> classOfS;
private Class<T> classOfT;
protected AbstractTwoWayConverter() {
Type typeA = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
Type typeB = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
this.classOfS = (Class) typeA;
this.classOfT = (Class) typeB;
}
public Set<ConvertiblePair> getConvertibleTypes() {
Set<ConvertiblePair> convertiblePairs = new HashSet<ConvertiblePair>();
convertiblePairs.add(new ConvertiblePair(classOfS, classOfT));
convertiblePairs.add(new ConvertiblePair(classOfT, classOfS));
return convertiblePairs;
}
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (classOfS.equals(sourceType.getType())) {
return this.convert((S) source);
} else {
return this.convertBack((T) source);
}
}
protected abstract T convert(S source);
protected abstract S convertBack(T target);
}
/**
* converter to convert between a userId and user.
* this class can be registered like so:
* conversionService.addConverter(new UserIdConverter (userDao));
*/
public class UserIdConverter extends AbstractTwoWayConverter<String, User> {
private final UserDao userDao;
@Autowired
public UserIdConverter(UserDao userDao) {
this.userDao = userDao;
}
@Override
protected User convert(String userId) {
return userDao.load(userId);
}
@Override
protected String convertBack(User target) {
return target.getUserId();
}
}
并添加到您的 XML 配置中:
...
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean" >
<property name="converters">
<set>
<bean class="com.x.y.UserIdConverter"/>
</set>
</property>
</bean>
...