在控制器之外使用 Spring Data Rest RepositoryEntityLinks

Ala*_*Hay 5 java spring-data-rest

根据当前 Spring Data Rest 手册的第 12.1 节,我想使用 RepositoryEntityLinks 类在我的代码中的各个位置获取资源的链接

12.1. 编程链接 有时您需要在您自己的自定义构建的 Spring MVC 控制器中添加指向导出资源的链接。可用的链接分为三个基本级别:

...

3 使用 Spring Data REST 的 RepositoryEntityLinks 实现。

http://docs.spring.io/spring-data/rest/docs/current/reference/html/#_programmatic_links

我注意到文档明确提到“...你自己定制的 Spring MVC 控制器”,而且它似乎是唯一可用的地方。我想在 Spring Security AuthenticationSuccessHandler 中使用配置的实例,但是应用程序无法启动并显示错误:

找不到 [org.springframework.data.rest.webmvc.support.RepositoryEntityLinks] 类型的合格 bean

我已经能够按预期成功地将它注入到控制器中。

我可以在 Spring MVC 控制器之外使用 RepositoryEntityLinks 类吗?

public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler
{
  @Autowired
  private RepositoryEntityLinks entityLinks;

  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
      Authentication authentication) throws IOException, ServletException
  {
    //do something with entityLinks
  }
}
Run Code Online (Sandbox Code Playgroud)

Dco*_*tez 0

是的你可以。我已成功在 Assembler 中使用它,它从 HATEOAS 模型生成链接。尽管在类的注入位置可能存在一些限制RepositoryEntityLinks,但可以肯定的是它可以在控制器之外使用。

下面你可以看到我的工作示例。如果有人想知道这个类扩展了ResourceAssemblerSupport,它是spring-hateoas模块的一部分。也许这就是在这里启用注入的东西。

@Component
public class UserAssembler extends ResourceAssemblerSupport<UserEntity, UserResource> {

    @Autowired
    private RepositoryEntityLinks repositoryEntityLinks;

    public UserAssembler() {
        super(UserController.class, UserResource.class);
    }

    @Override
    public UserResource toResource(UserEntity userEntity) {
        Link userLink = repositoryEntityLinks.linkToSingleResource(UserEntity.class, userEntity.getId());
        Link self = new Link(entryLink.getHref(), Link.REL_SELF);
        return new UserResource(userEntity, self);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这很有帮助,尽管 RepositoryEntityLinks 似乎只在 REST 请求的范围内工作。如果您正在编写直接与 Java 存储库接口交互的任何代码(例如,接口 `PersonRepository extends JpaRepository&lt;...&gt;`),那么 RepositoryEntityLinks 将因 IllegalStateException(“没有当前的 ServletRequestAttributes”)而终止,因为它试图使用 ServletUriComponentsBuilder.fromCurrentServletMapping() 构造 URI。您是否能够在 HTTP 请求范围之外使用它? (2认同)