我正在尝试使用通用服务层和存储库层通过RestTemplate
从后端服务中检索对象,我知道该后端服务将有效载荷序列化为正确类型Event
。
这是Event
类:
@Data
@Entity
@Table(name = "event")
@NoArgsConstructor
@AllArgsConstructor
public class Event extends BaseEntity {
@Column(name = "entity_id")
private long entityId;
@Column(name = "entity_type")
private String entityType;
@Column(name = "type")
private String type;
}
和ViewCommand<T>
类:
@Getter
@Setter
@NoArgsConstructor
public class ViewCommand<T extends BaseEntity> {
private List<T> results;
}
使用Spring Boot MVC通过Controller-> Service-> Repository服务于视图的前端服务,该存储库使用RestTemplate
将请求发送到Backend服务。
这是控制器:
@Controller
public class EventController extends BaseController {
private static final String PREFIX = "events";
@Autowired
private GenericService<Event> genericService;
@GetMapping(PREFIX + "/{page}")
public String events(final Model model) {
ViewCommand<Event> command = genericService.list(PREFIX, Event.class.getName(), 0);
model.addAttribute("command", command);
return "events";
}
}
通用服务类:
@Service
public class GenericService<T extends BaseEntity> {
@Autowired
private GenericRepository<T> genericRepository;
public ViewCommand<T> list(String prefix, String className, int page) {
return genericRepository.list(new ParameterizedTypeReference<>() {}, prefix, className, page);
}
}
通用存储库类:
@Repository
public class GenericRepository<T extends BaseEntity> extends BaseRepository {
private static final String LIST = "%s/list/%s/%s";
@Value("${backend.uri}")
private String backendUri;
@Autowired
private RestTemplate template;
public ViewCommand<T> list(ParameterizedTypeReference<ViewCommand<T>> responseType, String prefix, String type, int page) {
ViewCommand<T> body = template.exchange(backendUri + format(LIST, prefix, type, page), GET, getEntity(), responseType).getBody();
return body;
}
}
有人可以告诉我为什么results
中的ViewCommand<T>
列表反序列化为BaseEntity
而不是Event
的列表吗?
在使用T
时Java没有选择类型ParameterizedTypeReference
的地方,我在哪里出错?