How can I use a custom ID conversion with DomainCl

2019-09-11 21:11发布

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.

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.

Is there any non-invasive way to intercept the parameter and transform it before it's passed to the RepositoryInvoker?

1条回答
对你真心纯属浪费
2楼-- · 2019-09-11 22:05

easiest is if you create your own Formatter

like:

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 is used to bring a lot of beans into the context, see its javadoc - it's very informative

best

查看更多
登录 后发表回答