Deserialize class with @AutoValue annotation during getting from cache in SpringBoot application

831 views Asked by At

I've created a value class with com.google.auto.value.AutoValue annotation:

@AutoValue
@JsonDeserialize(builder = AutoValue_Company.Builder.class)
public abstract class Company {

public static Builder newBuilder() {
    return new AutoValue_Company.Builder();
}

@JsonProperty("id")
public abstract long id();

@JsonProperty("description")
public abstract String description();

@JsonProperty("websiteUrl")
public abstract String websiteUrl();

@AutoValue.Builder
public interface Builder {
    @JsonProperty("id")
    Builder id(long id);

    @JsonProperty("description")
    Builder description(String description);

    @JsonProperty("websiteUrl")
    Builder websiteUrl(String url);

    Company build();
}
}

Instance of such class is received from service and result is cached in Redis:

@Cacheable(value = "company")
public Company getValue(String id)

Here is the config of RedisCacheManager:

@Bean(name = "valueCacheManager")
public RedisCacheManager valueCacheManager(final RedisConnectionFactory connectionFactory) {
    final RedisCacheWriter redisCacheWriter = RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
    RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
    cacheConfiguration = cacheConfiguration.entryTtl(Duration.ofSeconds(100));
    return new RedisCacheManager(redisCacheWriter, cacheConfiguration);
}

As a result the issue that is connected to deserialization:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class com.test.models.AutoValue_Company and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
2

There are 2 answers

0
Uladzislau Kaminski On BEST ANSWER

The solution was found by changing serializer GenericJackson2JsonRedisSerializer to Jackson2JsonRedisSerializer<>(Company.class)

So the cache config now looks like that:

@Bean(name = "valueCacheManager")
public RedisCacheManager valueCacheManager(final RedisConnectionFactory connectionFactory) {
    final RedisCacheWriter redisCacheWriter = RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
    RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
             .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer<>(Company.class)));
    cacheConfiguration = cacheConfiguration.entryTtl(Duration.ofSeconds(100));
    return new RedisCacheManager(redisCacheWriter, cacheConfiguration);
}
0
matejko219 On

Maybe you should name your methods using getters convention e.g. getId() etc? I think this is related.