在我的Spring Boot Web应用程序中,我有一个JPA实体Medium
,它记录有关上传文件的信息。
我有一个基本的Spring Data Rest存储库来处理通用操作:
@RepositoryRestResource(path = "/media")
public interface MediumRepository extends CrudRepository<Medium, Long> {
}
但是,我需要客户端使用HTTP分段上传来上传文件,然后创建一个Medium
记录并在响应中返回它。响应的结构应与调用repository.save()
相同。我无法弄清楚的是如何添加HATEOAS元数据。显然,如果我回来
return mediumRepository.save(medium);
它将返回实体的基本JSON表示,没有HATEOAS。我already learned我应该使用PersistentEntityResourceAssembler
。
所以,我当前的控制器代码是:
@RestController
@RequestMapping("/upload")
public class MediaEndpoint {
@Autowired
private MediumRepository mediumRepository;
@RequestMapping(method = POST)
public PersistentEntityResource uploadMedium(
@RequestPart MultipartFile data,
PersistentEntityResourceAssembler persistentEntityResourceAssembler) {
Medium medium = new Medium();
// setup of the medium instance
Medium savedMedium = mediumRepository.save(medium);
return persistentEntityResourceAssembler.toResource(savedMedium);
}
}
但是,我无法将persistentEntityResourceAssembler
注入到方法中 - 我正在
Failed to instantiate [org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.<init>()
我该如何实现?
答案 0 :(得分:1)
尝试使用@RepositoryRestController代替@RestController。
答案 1 :(得分:0)
关注Cepr0's answer后,我将控制器更改为@RepositoryRestController
,但我遇到了异常
Circular view path [upload]: would dispatch back to the current handler URL [/upload] again.
Check your ViewResolver setup! (Hint: This may be the result of an unspecified view,
due to default view name generation.)
我found RepositoryRestController
未使用@ResponseBody
进行注释,并且应该返回ResponseEntity
,因此我将代码更改为以下内容:
@RepositoryRestController
@RequestMapping("/upload")
public class MediaEndpoint {
@Autowired
private MediumRepository mediumRepository;
@RequestMapping(method = POST)
public ResponseEntity<PersistentEntityResource> uploadMedium(
@RequestPart MultipartFile data,
PersistentEntityResourceAssembler persistentEntityResourceAssembler) {
Medium medium = new Medium();
// setup of the medium instance
Medium savedMedium = mediumRepository.save(medium);
return ResponseEntity.ok(persistentEntityResourceAssembler.toResource(savedMedium));
}
}
这给了我一个很好的JSON响应和HATEOAS元数据。
或者,使用@ResponseBody
注释方法或控制器的方式相同。