我有一个 Spring Data Rest webmvc 应用程序,我想为批处理操作添加一些自定义功能。
我创建了一个 Controller ,并将其混合到 uri 命名空间中,但我希望它能够接受像自定义 /search
这样的 URI查询可以,而不仅仅是一个 ID。
我已尝试注册自定义 <String, Long>
转换器(我的实体有一个 Long
ID 类型,但这似乎被忽略了。有没有办法配置我的 Controller ,使其采用自动实现的 SDR Controller 的行为?
即使我可以调用某种方法来自动解析实体的 URI,它也可以正常工作(因为我可以在我的 Controller 中简单地接受 String
)
这就是我所在的地方。
@Configuration
public class CustomWebConfiguration extends WebMvcConfigurationSupport {
//irrelevant code omitted
@Bean
public DomainClassConverter<?> domainClassConverter() {
DomainClassConverter<FormattingConversionService> dc = new DomainClassConverter<FormattingConversionService>(mvcConversionService());
return dc;
}
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(String.class, Long.class, testConverter());
}
@Bean
Converter<String, Long> testConverter() {
return new Converter<String, Long>() {
@Override
public Long convert(String source) {
//this code does _not_ get run at any point
if (source.indexOf('/') == -1) { return Long.parseLong(source); }
source = source.substring(source.lastIndexOf('/') + 1);
Long id = Long.parseLong(source);
return id;
}
};
}
}
SDR 配置
@Configuration
@EnableHypermediaSupport(type = { HypermediaType.HAL })
public class CustomRestConfiguration extends RepositoryRestMvcConfiguration {
@Override
public RepositoryRestConfiguration config() {
RepositoryRestConfiguration config = super.config();
config.setBasePath("/api");
config.exposeIdsFor(ApplicationMembership.class);
return config;
}
}
还有我的(人为的) Controller :
ApplicationType 是我的实体之一,由 SDR/存储库魔法正确管理
@BasePathAwareController
@RepositoryRestController
@RequestMapping("applications/special")
public class ApplicationExtensionController {
@RequestMapping("a")
public ResponseEntity<?> reply(@RequestParam("type") ApplicationType type) {
return new ResponseEntity<String>(type.getIcon(), HttpStatus.OK);
}
}
我已经环顾四周,但无法完全完成任何工作。当我创建 <String, ApplicationType>
使用存储库的转换器,它也不会被调用,因为 DomainClassConverter 只是调用其底层 <String, Long>
转换器(显然失败了,因为它无法正确地将 types/1
解析为 long。
感谢您的帮助!
忘了说
- Spring Data Rest 2.4.0
- Spring HATEOAS 0.19.0
- Spring 4.2.1
使用 JPA 存储库
最佳答案
事实证明,我在添加转换器方面走在了正确的轨道上,但不幸的是我使用了错误的配置方法。
通过将我的 testConverter()
bean 移动到 RepositoryRestMvcConfiguration
扩展配置类,然后添加
@Override
public void configureConversionService(ConfigurableConversionService service) {
service.addConverter(testConverter());
}
并按预期工作。我现在觉得一开始就把它放在错误的地方有点傻,但希望这能帮助别人!
关于java - 在自定义 Controller 中接受 Spring Data REST URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32513123/