Spring Data REST 暴露了一个集合资源,该资源以导出的存储库所处理的域类的非大写复数命名。
资源的名称和路径都可以通过在版本库接口上使用@RepositoryRestResource来定制。
也就是说,@RepositoryRestResource注解是可选的,用于定制REST端点。
例如,有一个存储库Station,如果不使用@RepositoryRestResource注解,
public interface StationRepository extends MongoRepository {
}
Spring Data REST 暴露的api端点是/stations
,
如果使用@RepositoryRestResource注解自定义,
@RepositoryRestResource(collectionResourceRel = "station", path = "station")
public interface StationRepository extends MongoRepository {
}
Spring Data REST 暴露的api端点是我们自定义的/station
。
@RepositoryRestController注解可以帮助我们客户化Spring Data REST 暴露的api端点的功能。
例如,api端点/station/{id}
默认返回这个Station的真实数据,
curl -X GET http://localhost:8181/station/2008
{
"name" : "Little West St & 1 Pl",
"region_id" : "71",
"lon" : -74.01677685,
"lat" : 40.70569254,
"eightd_has_key_dispenser" : false,
"legacy_id" : "2008",
"rental_methods" : [ "KEY", "CREDITCARD" ],
"external_id" : "66dc90d5-0aca-11e7-82f6-3863bb44ef7c",
"capacity" : 35,
"short_name" : "5001.08",
"electric_bike_surcharge_waiver" : false,
"station_type" : "classic",
"eightd_station_services" : [ ],
"has_kiosk" : true,
"rental_uris" : {
"android" : "https://bkn.lft.to/lastmile_qr_scan",
"ios" : "https://bkn.lft.to/lastmile_qr_scan"
},
"_links" : {
"self" : {
"href" : "http://localhost:8181/station/2008"
},
"station" : {
"href" : "http://localhost:8181/station/2008"
}
}
}
我们想客户化api端点/station/{id}
的功能,通过@RepositoryRestController注解实现自定义的功能。需要注意的是,我们想覆盖哪些Spring Data Rest默认的api端点的功能,RequestMapping的方法类型和端点必须和Spring Data Rest默认暴露的方法类型和端点一致。
@RepositoryRestController
//@RestController
public class StationController {
@Resource
StationRepository stationRepository;
@RequestMapping(method = RequestMethod.GET, value = "/station/{id}")
public @ResponseBody HttpEntity getStation(@PathVariable String id) {
Station station = Station.builder().id(id).build();
return ResponseEntity.ok(station);
}
}
实现后的效果,
curl -X GET http://localhost:8181/station/2008
{
"id" : "2008",
"name" : null,
"region_id" : null,
"lon" : 0.0,
"lat" : 0.0,
"eightd_has_key_dispenser" : false,
"legacy_id" : null,
"rental_methods" : null,
"external_id" : null,
"capacity" : 0,
"short_name" : null,
"electric_bike_surcharge_waiver" : false,
"station_type" : null,
"eightd_station_services" : null,
"has_kiosk" : false,
"rental_uris" : null
}
完结!