[英]Resolving entity URI in custom controller (Spring HATEOAS)
我有一个基于 spring-data-rest 的项目,它还有一些自定义端点。
为了发送 POST 数据,我正在使用 json 之类的
{
"action": "REMOVE",
"customer": "http://localhost:8080/api/rest/customers/7"
}
这对于 spring-data-rest 很好,但不适用于自定义控制器。
例如:
public class Action {
public ActionType action;
public Customer customer;
}
@RestController
public class ActionController(){
@Autowired
private ActionService actionService;
@RestController
public class ActionController {
@Autowired
private ActionService actionService;
@RequestMapping(value = "/customer/action", method = RequestMethod.POST)
public ResponseEntity<ActionResult> doAction(@RequestBody Action action){
ActionType actionType = action.action;
Customer customer = action.customer;//<------There is a problem
ActionResult result = actionService.doCustomerAction(actionType, customer);
return ResponseEntity.ok(result);
}
}
当我打电话
curl -v -X POST -H "Content-Type: application/json" -d '{"action": "REMOVE","customer": "http://localhost:8080/api/rest/customers/7"}' http://localhost:8080/customer/action
我有答案
{
"timestamp" : "2016-05-12T11:55:41.237+0000",
"status" : 400,
"error" : "Bad Request",
"exception" : "org.springframework.http.converter.HttpMessageNotReadableException",
"message" : "Could not read document: Can not instantiate value of type [simple type, class model.user.Customer] from String value ('http://localhost:8080/api/rest/customers/7'); no single-String constructor/factory method\n at [Source: java.io.PushbackInputStream@73af10c6; line: 1, column: 33] (through reference chain: api.controller.Action[\"customer\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class logic.model.user.Customer] from String value ('http://localhost:8080/api/rest/customers/7'); no single-String constructor/factory method\n at [Source: java.io.PushbackInputStream@73af10c6; line: 1, column: 33] (through reference chain: api.controller.Action[\"customer\"])",
"path" : "/customer/action"
* Closing connection 0
}
原因是 spring 无法将 URI 转换为 Customer 实体。
有没有办法使用 spring-data-rest 机制通过 URI 解析实体?
我只有一个想法 - 使用自定义 JsonDeserializer 和解析 URI 来提取 entityId 并向存储库发出请求。 但是,如果我有像“ http://localhost:8080/api/rest/customers/8/product ”这样的 URI,那么这个策略对我没有帮助,在这种情况下我没有product.Id值。
我也遇到同样的问题很长时间了,并通过以下方式解决了它。 @Florian 走在正确的轨道上,感谢他的建议,我找到了一种自动进行转换的方法。 需要几个部分:
对于第 1 点,实现可以缩小到以下内容
import org.springframework.context.ApplicationContext;
import org.springframework.data.mapping.context.PersistentEntities;
import org.springframework.data.repository.support.DomainClassConverter;
import org.springframework.data.rest.core.UriToEntityConverter;
import org.springframework.format.support.DefaultFormattingConversionService;
public class UriToEntityConversionService extends DefaultFormattingConversionService {
private UriToEntityConverter converter;
public UriToEntityConversionService(ApplicationContext applicationContext, PersistentEntities entities) {
new DomainClassConverter<>(this).setApplicationContext(applicationContext);
converter = new UriToEntityConverter(entities, this);
addConverter(converter);
}
public UriToEntityConverter getConverter() {
return converter;
}
}
对于第 2 点,这是我的解决方案
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.deser.ValueInstantiator;
import com.fasterxml.jackson.databind.deser.std.StdValueInstantiator;
import your.domain.RootEntity; // <-- replace this with the import of the root class (or marker interface) of your domain
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.data.mapping.PersistentEntity;
import org.springframework.data.mapping.context.PersistentEntities;
import org.springframework.data.rest.core.UriToEntityConverter;
import org.springframework.util.Assert;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Optional;
public class RootEntityFromUriDeserializer extends BeanDeserializerModifier {
private final UriToEntityConverter converter;
private final PersistentEntities repositories;
public RootEntityFromUriDeserializer(PersistentEntities repositories, UriToEntityConverter converter) {
Assert.notNull(repositories, "Repositories must not be null!");
Assert.notNull(converter, "UriToEntityConverter must not be null!");
this.repositories = repositories;
this.converter = converter;
}
@Override
public BeanDeserializerBuilder updateBuilder(DeserializationConfig config, BeanDescription beanDesc, BeanDeserializerBuilder builder) {
PersistentEntity<?, ?> entity = repositories.getPersistentEntity(beanDesc.getBeanClass());
boolean deserializingARootEntity = entity != null && RootEntity.class.isAssignableFrom(entity.getType());
if (deserializingARootEntity) {
replaceValueInstantiator(builder, entity);
}
return builder;
}
private void replaceValueInstantiator(BeanDeserializerBuilder builder, PersistentEntity<?, ?> entity) {
ValueInstantiator currentValueInstantiator = builder.getValueInstantiator();
if (currentValueInstantiator instanceof StdValueInstantiator) {
EntityFromUriInstantiator entityFromUriInstantiator =
new EntityFromUriInstantiator((StdValueInstantiator) currentValueInstantiator, entity.getType(), converter);
builder.setValueInstantiator(entityFromUriInstantiator);
}
}
private class EntityFromUriInstantiator extends StdValueInstantiator {
private final Class entityType;
private final UriToEntityConverter converter;
private EntityFromUriInstantiator(StdValueInstantiator src, Class entityType, UriToEntityConverter converter) {
super(src);
this.entityType = entityType;
this.converter = converter;
}
@Override
public Object createFromString(DeserializationContext ctxt, String value) throws IOException {
URI uri;
try {
uri = new URI(value);
} catch (URISyntaxException e) {
return super.createFromString(ctxt, value);
}
return converter.convert(uri, TypeDescriptor.valueOf(URI.class), TypeDescriptor.valueOf(entityType));
}
}
}
然后对于第 3 点,在自定义 RepositoryRestConfigurerAdapter 中,
public class MyRepositoryRestConfigurer extends RepositoryRestConfigurerAdapter {
@Override
public void configureJacksonObjectMapper(ObjectMapper objectMapper) {
objectMapper.registerModule(new SimpleModule("URIDeserializationModule"){
@Override
public void setupModule(SetupContext context) {
UriToEntityConverter converter = conversionService.getConverter();
RootEntityFromUriDeserializer rootEntityFromUriDeserializer = new RootEntityFromUriDeserializer(persistentEntities, converter);
context.addBeanDeserializerModifier(rootEntityFromUriDeserializer);
}
});
}
}
这对我来说很顺利,并且不会干扰框架的任何转换(我们有许多自定义端点)。 在第 2 点中,目的是仅在以下情况下从 URI 启用实例化:
这更像是一个旁注而不是真正的答案,但不久前我设法通过使用 SDR 中使用的方法(更粗略)复制并粘贴自己一个类来解析 URL 中的实体。 可能有更好的方法,但在那之前,也许这会有所帮助......
@Service
public class EntityConverter {
@Autowired
private MappingContext<?, ?> mappingContext;
@Autowired
private ApplicationContext applicationContext;
@Autowired(required = false)
private List<RepositoryRestConfigurer> configurers = Collections.emptyList();
public <T> T convert(Link link, Class<T> target) {
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
PersistentEntities entities = new PersistentEntities(Arrays.asList(mappingContext));
UriToEntityConverter converter = new UriToEntityConverter(entities, conversionService);
conversionService.addConverter(converter);
addFormatters(conversionService);
for (RepositoryRestConfigurer configurer : configurers) {
configurer.configureConversionService(conversionService);
}
URI uri = convert(link);
T object = target.cast(conversionService.convert(uri, TypeDescriptor.valueOf(target)));
if (object == null) {
throw new IllegalArgumentException(String.format("%s '%s' was not found.", target.getSimpleName(), uri));
}
return object;
}
private URI convert(Link link) {
try {
return new URI(link.getHref());
} catch (Exception e) {
throw new IllegalArgumentException("URI from link is invalid", e);
}
}
private void addFormatters(FormatterRegistry registry) {
registry.addFormatter(DistanceFormatter.INSTANCE);
registry.addFormatter(PointFormatter.INSTANCE);
if (!(registry instanceof FormattingConversionService)) {
return;
}
FormattingConversionService conversionService = (FormattingConversionService) registry;
DomainClassConverter<FormattingConversionService> converter = new DomainClassConverter<FormattingConversionService>(
conversionService);
converter.setApplicationContext(applicationContext);
}
}
是的,这门课的部分内容很可能根本没用。 在我的辩护中,这只是一个简短的黑客,我从来没有真正需要它,因为我首先发现了其他问题;-)
对于带有@RequestBody
HAL,使用Resource<T>
作为方法参数而不是实体Action
以允许转换相关资源 URI
public ResponseEntity<ActionResult> doAction(@RequestBody Resource<Action> action){
我不敢相信。 在 MONTH(!) 把我的头围绕在这个问题上之后,我设法解决了这个问题!
一些介绍的话:
Spring HATEOAS 使用 URI 作为对实体的引用。 它为获取给定实体的这些 URI 链接提供了极大的支持。 例如,当客户端请求引用其他子实体的实体时,客户端将收到这些 URI。 很高兴与之合作。
GET /users/1
{
"username": "foobar",
"_links": {
"self": {
"href": "http://localhost:8080/user/1" //<<<== HATEOAS Link
}
}
}
REST 客户端仅适用于这些 uri。 REST 客户端不得知道这些 URI 的结构。 REST 客户端不知道 URI 字符串末尾有一个数据库内部 ID。
到目前为止一切顺利。 但是 spring 数据 HATEOAS 不提供任何将 URI 转换回相应实体(从数据库加载)的功能。 每个人都需要在自定义 REST 控制器中使用它。 (见上面的问题)
考虑一个示例,您希望在自定义 REST 控制器中与用户一起工作。 客户端将发送此请求
POST /checkAdress
{
user: "/users/1"
someMoreOtherParams: "...",
[...]
}
自定义 REST 控制器应如何从(字符串)uri 反序列化到 UserModel? 我找到了一种方法:您必须在 RepositoryRestConfigurer 中配置 Jackson 反序列化:
RepositoryRestConfigurer.java
public class RepositoryRestConfigurer extends RepositoryRestConfigurerAdapter {
@Autowired
UserRepo userRepo;
@Override
public void configureJacksonObjectMapper(ObjectMapper objectMapper) {
SimpleModule module = new SimpleModule();
module.addDeserializer(UserModel.class, new JsonDeserializer<UserModel>() {
@Override
public UserModel deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
String uri = p.getValueAsString();
//extract ID from URI, with regular expression (1)
Pattern regex = Pattern.compile(".*\\/" + entityName + "\\/(\\d+)");
Matcher matcher = regex.matcher(uri);
if (!matcher.matches()) throw new RuntimeException("This does not seem to be an URI for an '"+entityName+"': "+uri);
String userId = matcher.group(1);
UserModel user = userRepo.findById(userId)
.orElseThrow(() -> new RuntimeException("User with id "+userId+" does not exist."))
return user;
}
});
objectMapper.registerModule(module);
}
}
(1) 这个字符串解析很丑。 我知道。 但这只是 org.springframework.hateoas.EntityLinks 及其实现的反面。 而 spring-hateos 的作者固执地拒绝提供两个方向的实用方法。
我得到了以下解决方案。 这有点hackish,但有效。
首先,将 URI 转换为实体的服务。
实体转换器
import java.net.URI;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.data.geo.format.DistanceFormatter;
import org.springframework.data.geo.format.PointFormatter;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mapping.context.PersistentEntities;
import org.springframework.data.repository.support.DefaultRepositoryInvokerFactory;
import org.springframework.data.repository.support.DomainClassConverter;
import org.springframework.data.repository.support.Repositories;
import org.springframework.data.rest.core.UriToEntityConverter;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.hateoas.Link;
import org.springframework.stereotype.Service;
@Service
public class EntityConverter {
@Autowired
private MappingContext<?, ?> mappingContext;
@Autowired
private ApplicationContext applicationContext;
@Autowired(required = false)
private List<RepositoryRestConfigurer> configurers = Collections.emptyList();
public <T> T convert(Link link, Class<T> target) {
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
Repositories repositories = new Repositories(applicationContext);
UriToEntityConverter converter = new UriToEntityConverter(
new PersistentEntities(Collections.singleton(mappingContext)),
new DefaultRepositoryInvokerFactory(repositories),
repositories);
conversionService.addConverter(converter);
addFormatters(conversionService);
for (RepositoryRestConfigurer configurer : configurers) {
configurer.configureConversionService(conversionService);
}
URI uri = convert(link);
T object = target.cast(conversionService.convert(uri, TypeDescriptor.valueOf(target)));
if (object == null) {
throw new IllegalArgumentException(String.format("registerNotFound", target.getSimpleName(), uri));
}
return object;
}
private URI convert(Link link) {
try {
return new URI(link.getHref().replace("{?projection}", ""));
} catch (Exception e) {
throw new IllegalArgumentException("invalidURI", e);
}
}
private void addFormatters(FormatterRegistry registry) {
registry.addFormatter(DistanceFormatter.INSTANCE);
registry.addFormatter(PointFormatter.INSTANCE);
if (!(registry instanceof FormattingConversionService)) {
return;
}
FormattingConversionService conversionService = (FormattingConversionService) registry;
DomainClassConverter<FormattingConversionService> converter = new DomainClassConverter<FormattingConversionService>(
conversionService);
converter.setApplicationContext(applicationContext);
}
}
其次,一个组件要能够在 Spring 上下文之外使用EntityConverter
。
应用上下文持有者
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getContext() {
return context;
}
}
第三,将另一个实体作为输入的实体构造函数。
我的实体
public MyEntity(MyEntity entity) {
property1 = entity.property1;
property2 = entity.property2;
property3 = entity.property3;
// ...
}
第四,实体构造函数,以String
为输入,应该是URI。
我的实体
public MyEntity(String URI) {
this(ApplicationContextHolder.getContext().getBean(EntityConverter.class).convert(new Link(URI.replace("{?projection}", "")), MyEntity.class));
}
或者,我已将上面的部分代码移至Utils
类。
我通过查看问题帖子中的错误消息得出了这个解决方案,我也收到了。 Spring 不知道如何从String
构造对象? 我会告诉它如何...
但是,就像评论中所说的那样,不适用于嵌套实体的 URI。
我的解决方案将是一些紧凑的。 不确定它对所有情况都有用,但对于像.../entity/{id}
这样的简单关系它可以解析。 我已经在 SDR & Spring Boot 2.0.3.RELEASE 上测试过了
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mapping.context.PersistentEntities;
import org.springframework.data.repository.support.Repositories;
import org.springframework.data.repository.support.RepositoryInvokerFactory;
import org.springframework.data.rest.core.UriToEntityConverter;
import org.springframework.hateoas.Link;
import org.springframework.stereotype.Service;
import java.net.URI;
import java.util.Collections;
@Service
public class UriToEntityConversionService {
@Autowired
private MappingContext<?, ?> mappingContext; // OOTB
@Autowired
private RepositoryInvokerFactory invokerFactory; // OOTB
@Autowired
private Repositories repositories; // OOTB
public <T> T convert(Link link, Class<T> target) {
PersistentEntities entities = new PersistentEntities(Collections.singletonList(mappingContext));
UriToEntityConverter converter = new UriToEntityConverter(entities, invokerFactory, repositories);
URI uri = convert(link);
Object o = converter.convert(uri, TypeDescriptor.valueOf(URI.class), TypeDescriptor.valueOf(target));
T object = target.cast(o);
if (object == null) {
throw new IllegalArgumentException(String.format("%s '%s' was not found.", target.getSimpleName(), uri));
}
return object;
}
private URI convert(Link link) {
try {
return new URI(link.getHref());
} catch (Exception e) {
throw new IllegalArgumentException("URI from link is invalid", e);
}
}
}
用法:
@Component
public class CategoryConverter implements Converter<CategoryForm, Category> {
private UriToEntityConversionService conversionService;
@Autowired
public CategoryConverter(UriToEntityConversionService conversionService) {
this.conversionService = conversionService;
}
@Override
public Category convert(CategoryForm source) {
Category category = new Category();
category.setId(source.getId());
category.setName(source.getName());
category.setOptions(source.getOptions());
if (source.getParent() != null) {
Category parent = conversionService.convert(new Link(source.getParent()), Category.class);
category.setParent(parent);
}
return category;
}
}
请求 JSON,如:
{
...
"parent": "http://localhost:8080/categories/{id}",
...
}
不幸的是,使用 Spring Data REST 的UriToEntityConverter (可以将 URI 转换为实体的通用转换器)没有作为Bean或作为Service导出。
所以我们不能直接@Autowired
它,但它在默认格式转换服务中注册为转换器。
因此,我们设法使用@Autowired
默认格式转换服务并使用它们将 URI 转换为实体,例如:
@RestController
@RequiredArgsConstructor
public class InstanceController {
private final DefaultFormattingConversionService formattingConversionService;
@RequestMapping(path = "/api/instances", method = {RequestMethod.POST})
public ResponseEntity<?> create(@RequestBody @Valid InstanceDTO instanceDTO) { // get something what you want from request
// ...
// extract URI from any string what you want to process
final URI uri = "..."; // http://localhost:8080/api/instances/1
// convert URI to Entity
final Instance instance = formattingConversionService.convert(uri, Instance.class); // Instance(id=1, ...)
// ...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.