我使用的是Spring Data Rest 3.3.1。
我有域对象(这只是一个例子):
@Data @Getter @Setter
@Entity
public class Figure {
@Id private long id;
private int volume;
}
我有这个实体的存储库:
@RepositoryRestResource
public interface FigureRepository extends CrudRepository<Figure, Long> {}
因此,spring自动为POSTing图形实体创建方法。例如:
POST localhost:8080/figures
{
"volume": 1000
}
但我希望将自定义对象传递给POST方法,并将其转换为所需的实体,例如
POST localhost:8080/figures
{
"length": 10,
"width": 10,
"height": 10
}
和转换器的示例:
class FigureDtoConverter implements Converter<FigureDto, Figure> {
@Override
Figure convert(FigureDto dto) {
Figure f = new Figure();
f.setVolume(dto.getLength() * dto.getWidth() * dto.getHeight());
return f;
}
}
如何在不创建自定义控制器的情况下做到这一点?因为如果我创建了控制器,就会丢失一些有用的spring特性,比如事件处理、验证等
发布于 2020-07-04 11:34:42
不行。你必须创建你的控制器。
使用不同的请求映射路径而不是/figures
可以保留Spring Data REST端点
POST localhost:8080/figures
{
"volume": 1000
}
POST localhost:8080/create-figure-by-measurement
{
"length": 10,
"width": 10,
"height": 10
}
发布于 2020-07-04 11:35:24
创建一个包含您想要传递的字段的POJO。
public class Edges {
Integer length;
Integer width;
Integer height; //getters and setters
}
您可以使用下面的代码发出post请求
{
"length": 10,
"width": 10,
"height": 10
}
并在控制器中获取Edges
的对象并将其转换为Figure
@PostMapping("/figure")
public String getEdges(@RequestBody Edges edges){
//...
}
https://stackoverflow.com/questions/62723302
复制相似问题