簡體   English   中英

在 Controller 之外使用 Spring 數據 Rest RepositoryEntityLinks

[英]Using Spring Data Rest RepositoryEntityLinks outside of Controller

根據當前 Spring 數據 Z55276C10D84E1DF7713B441E76E14F 手冊的第 12.1 節,我想使用 RepositoryEntityLinks class 在我的代碼中的各個位置獲取資源的鏈接

12.1. 程序鏈接有時您需要在自己的自定義構建的 Spring MVC controller中添加指向導出資源的鏈接。 共有三個基本級別的鏈接可用:

...

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

我已經能夠按預期成功地將其注入 controller。

我可以在 Spring MVC Controller 之外使用 RepositoryEntityLinks class 嗎?

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
  }
}

是的你可以。 我已成功在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);
    }
}

以下對我有用:

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class RestApiIntegrationTests {

    @Autowired
    private RepositoryEntityLinks repositoryEntityLinks;

    @BeforeEach
    public void initServletRequestAttributes() {
        MockHttpServletRequest request = new MockHttpServletRequest();
        ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
        RequestContextHolder.setRequestAttributes(requestAttributes);
    }

    @Test
    void test() { 
        System.out.println(repositoryEntityLinks.linkToCollectionResource(SomeClass.class));
    }

}

該代碼基於spring-data-rest-tests-coreAbstractControllerIntegrationTestsTestMvcClient

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM