@
kran 例如 redis
官方默认是可用,但是用户想用 json 可视化
@
Configuration(proxyBeanMethods = false)
@
ConditionalOnClass(RedisOperations.class)
@
EnableConfigurationProperties(RedisProperties.class)
@
Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {
@
Bean @
ConditionalOnMissingBean(name = "redisTemplate")
@
ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@
Bean @
ConditionalOnMissingBean @
ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
return new StringRedisTemplate(redisConnectionFactory);
}
}
然后用户配置
@
Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
RedisSerializer<Object> redisSerializer = getRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setValueSerializer(redisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.setHashValueSerializer(redisSerializer);
redisTemplate.setDefaultSerializer(redisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@
Bean public RedisSerializer<Object> getRedisSerializer() {
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
/*
* 支持 JDK8 LocalDateTime
*/
om.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule())
.registerModule(new ParameterNamesModule());
serializer.setObjectMapper(om);
return serializer;
}
自己的自定义去覆盖。