我正在创建一个基于 spring-boot-starter-parent 2.6.1 的服务,并使用 spring data rest 来公开我的 JPA 存储库:
public interface PointRepo extends CrudRepository<Point<?>, String> {}
Point
类型具有子类型 Quantity
和 Switch
,因此 GET /points
当前返回类似以下内容:
{
"_embedded" : {
"switches" : [ {
...
"_links" : {
"self" : {
"href" : "http://localhost:8080/switch/office_light"
},
...
}
}],
"quantities" : [ {
...
"_links" : {
"self" : {
"href" : "http://localhost:8080/quantity/office_temp"
},
...
}
}
由于我不打算公开端点
/switches
和 /quantities
,因此我希望所有 Point
都位于 _embedded.points
中,并且 self href 也指向 /points
。我想,我需要一个自定义的 LinkRelationProvider
所以我创建了这个:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class PointRelProvider extends EvoInflectorLinkRelationProvider {
@Override
public LinkRelation getCollectionResourceRelFor(final Class<?> type) {
return super.getCollectionResourceRelFor(Point.class);
}
@Override
public LinkRelation getItemResourceRelFor(Class<?> type) {
return super.getItemResourceRelFor(Point.class);
}
@Override
public boolean supports(LookupContext delimiter) {
return Point.class.isAssignableFrom(delimiter.getType());
}
}
我发现 bean 已创建,但它对输出没有任何影响。我在每个方法中都放置了断点,但没有一个方法被调用。有什么想法为什么会出现这种情况吗?
以下内容似乎对我有用,至少达到了我的断点被击中的程度:
@Configuration
public class RestConfiguration extends RepositoryRestConfigurerAdapter {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) {
config.setLinkRelationProvider(new DelegatingLinkRelationProvider(
new PointRelProvider(),
// the default Spring Data REST link relation provider as a fallback
new EvoInflectorLinkRelationProvider()
));
}
}
这样,就无需在
EvoInflectorLinkRelationProvider
中扩展 PointRelProvider
。您可以直接实施 LinkRelationProvider
。我还认为PointRelProvider
上的注释是不必要的,因为配置是手动完成的。