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)
是的你可以。我已成功在 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)
| 归档时间: |
|
| 查看次数: |
1123 次 |
| 最近记录: |