问题描述
我有一个 SQL 数据库,其中主键是 UUID,但 UUID 的规范字符串表示很长,我想在我的 URL 中使用缩短版本 (Base58).Spring Data 的 DomainClassConverter
会将 MVC 请求参数或路径变量转换为域对象,但我希望能够在将解析的 ID 传递到存储库之前对其进行修改.
I have a SQL database where primary keys are UUIDs, but the canonical string representation of a UUID is very long, and I would like to use a shortened version (Base58) in my URLs. Spring Data's DomainClassConverter
will convert MVC request parameters or path variables into domain objects, but I want to be able to modify the resolved ID before it's passed to the repository.
默认的 SpringDataWebConfiguration
使用上下文提供的 FormattingConversionService
创建一个 DomainClassConverter
,这可能是不安全的,可以随意修改.向方法参数添加注释可能会消除解释的歧义,但这两者都必须在整个地方复制,并且不能与 Spring Data REST 等外部控制器一起使用.将 (String parameter
->ID) 转换委托给转换服务的行为是硬连接在私有内部类中的,所以我无法在那里修改它.
The default SpringDataWebConfiguration
creates a DomainClassConverter
using a FormattingConversionService
supplied by the context, which presumably is not safe to arbitrarily mangle. Adding an annotation to the method parameters would potentially disambiguate the interpretation, but this would both have to be replicated all over the place and not work with external controllers such as Spring Data REST. The behavior of delegating the (String parameter
->ID) conversion to the conversion service is hard-wired in a private inner class, so I can't modify it there.
在传递给RepositoryInvoker
之前,是否有任何非侵入性的方法来拦截参数并对其进行转换?
Is there any non-invasive way to intercept the parameter and transform it before it's passed to the RepositoryInvoker
?
推荐答案
最简单的方法是创建自己的格式化程序
easiest is if you create your own Formatter
喜欢:
public class UserFormatter implements Formatter<User> {
@Autowired
UserRepository userRepository;
@Override
public User parse(String text, Locale locale) throws ParseException {
return userRepository.findOneByUsername(text);
}
@Override
public String print(User user, Locale locale) {
return user.getUsername();
}
}
然后在您的应用程序上下文中注册它:
then register it in your application context:
@Configuration
@EnableSpringDataWebSupport
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(userFormatter());
}
@Bean
public UserFormatter userFormatter() {
return new UserFormatter();
}
}
@EnableSpringDataWebSupport
用于将大量 bean 带入上下文,请参阅其 javadoc - 非常有用
@EnableSpringDataWebSupport
is used to bring a lot of beans into the context, see its javadoc - it's very informative
最好
这篇关于如何在 DomainClassConverter 中使用自定义 ID 转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!