【问题标题】:How to expose @EmbeddedId converters in Spring Data REST如何在 Spring Data REST 中公开 @EmbeddedId 转换器
【发布时间】:2014-12-02 16:14:48
【问题描述】:

有些实体具有复合主键,这些实体在暴露时具有不正确的链接,在 _links 内的 URL 中具有类的完整限定名称

点击链接也会出现此类错误 -

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type java.lang.String to type com.core.connection.domains.UserFriendshipId

我有 XML 配置的 Spring Repository 并启用了 jpa:repositories 并且 Respository 从 JpaRepository 扩展

我可以让 Repository 实现 org.springframework.core.convert.converter.Converter 来处理这个问题。目前正在获取如下链接-

_links: {
userByFriendshipId: {
href: "http://localhost:8080/api/userFriendships/com.core.connection.domains.UserFriendshipId@5b10/userByFriendId"
}

在 xml 配置中,我启用了 jpa:repositories 并在 Repositories 中启用了 @RestResource

【问题讨论】:

  • 我认为这里的解决方案将继承 RepositoryRestMvcConfiguration 并覆盖 configureConversionService。

标签: java spring spring-data spring-data-rest


【解决方案1】:

首先,您需要获得一个可用的链接。目前,您的复合 ID 公开为 com.core.connection.domains.UserFriendshipId@5b10。覆盖UserFriendshipIdtoString 方法就足以产生像2-3 这样有用的东西。

接下来您需要实现converter,以便2-3 可以转换回UserFriendshipId

class UserFriendShipIdConverter implements Converter<String, UserFriendshipId> {

  UserFriendShipId convert(String id) {
    ...
  }
}

最后你需要注册转换器。你已经建议覆盖configureConversionService

protected void configureConversionService(ConfigurableConversionService conversionService) {
   conversionService.addConverter(new UserFriendShipIdConverter());
} 

如果您更喜欢 XML 配置,可以按照 documentation 中的说明进行操作。

【讨论】:

    【解决方案2】:

    要扩展已接受的答案.. 使用 spring-boot 时,为了使其正常工作,我的扩展 RepositoryRestMvcConfiguration 的类也需要具有 @Configuration 注释。我还需要在我的 Spring Boot 应用程序类中添加以下注释:

    @SpringBootApplication
    @Import(MyConfiguration.class)
    public class ApplicationContext {
    
        public static void main(String[] args) {
            SpringApplication.run(ApplicationContext.class,args);
        }
    }
    

    我还在我的方法中调用了覆盖configureConversionService的超级方法:

        @Override
        protected void configureConversionService(ConfigurableConversionService conversionService) {
            super.configureConversionService(conversionService);
            conversionService.addConverter(new TaskPlatformIdConverter());
        }
    

    这会保留默认转换器,然后添加您的

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-30
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2018-02-23
    • 2016-12-07
    • 1970-01-01
    相关资源
    最近更新 更多