spring boot @Cachable 返回超类的所有字段填充空值

spring boot @Cachable returning all fields of superclasses filled with null values

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

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

@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 由几个字段组成。有些包含自定义 classes 的实例、它们的一些列表和其他简单的原始值。

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

我们使用 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);

响应 class 如下所示:

public class GetOrdersResponseDto implements Serializable {

    private String cacheSerial;

    private List<OrderResponseDto> orderResponseDtos;

}

并且问题仅发生在 OrderResponseDto 的字段中,这些字段是 OrderResponseDto 的超 class 的一部分。

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

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

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

如果您的对象是可序列化的并且扩展了一个不可序列化的对象,那么父对象的字段仅被初始化,而不是有用的 NotSerializeException,这就是为什么您将它们设置为空值.

您可以在单元测试中证明这一点。 这是一个可以重用的 - 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