Spring 引导@Cachable返回填充有空值的超类的所有字段



我们正面临一个奇怪的问题,我不明白发生了什么,希望其他人已经遇到了同样的问题,并且知道发生了什么。

我们编写了一个简单的 REST 服务,利用@Cachable:

@GetMapping(value = "/get/{" + PARAM_TENANT + "}/{" + PARAM_UID + "}")
@Cacheable(value = GET_ORDERS_BY_UID )
public GetOrdersResponseDto getOrdersByUid(@PathVariable final String tenant, @PathVariable final String uid) {
....
return new GetOrdersResponseDto(createCacheKey(), orderResponseDtos);
}

GetOrdersResponseDto 由几个字段组成。有些包含自定义类的实例,一些自定义类的列表和其他简单的基元值。

当从缓存中提供 GetOrdersResponseDto 响应时,存储在列表中并位于对象超类中的所有对象字段都填充空值。

我们使用 hazelcast 作为缓存实现。我们的缓存配置非常基本:

@Component
public class HazelcastConfig extends Config {
@Autowired
public HazelcastConfig(final ConfigClient configClient) {
super();
final GroupConfig groupConfig = getGroupConfig();
final String name = configClient
.getConfigPropertyValueOrThrow("public", "com.orderservice.hazelcast.group.name");
groupConfig.setName("foogroup");
final String password = configClient
.getConfigPropertyValueOrThrow("public", "com.orderservice.hazelcast.group.password");
groupConfig.setPassword(password);

响应类如下所示:

public class GetOrdersResponseDto implements Serializable {
private String cacheSerial;
private List<OrderResponseDto> orderResponseDtos;
}

并且问题只发生在属于 OrderResponseDto 超类的 OrderResponseDto 字段。

我希望有人能给我们一个提示,这种奇怪行为的原因是什么。

编辑:我发现,问题只发生在存储在列表中的对象上......

这是Java的行为。见 https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html

如果您的对象是可序列化的,并且扩展了不可序列化的对象,则父对象的字段仅初始化,而不是有用的NotSerializeException,这就是将它们作为 null 的原因。

您可以在单元测试中证明这一点。 这是一个可以重用的 - https://github.com/hazelcast/hazelcast-code-samples/blob/master/serialization/hazelcast-airlines/the-code/src/test/java/com/hazelcast/samples/serialization/hazelcast/airlines/V1FlightTest.java

最新更新