@EnableConfigurationProperties
CacheProperties类使用了@ConfigurationProperties注解,可以从配置文件加载配置参数值赋类里各个成员变量,@EnableConfigurationProperties
根据字面意思判断就是将使用@ConfigurationProperties注解的类注入到Spring IOC容器里,交给Spring管理
@EnableConfigurationProperties(value = CacheProperties.class)
–相当于–>
@Component@ConfigurationProperties(prefix = “spring.cache”)
```java
/**
* 参考 RedisCacheConfiguration配置类,照着写就行
*
* a@see org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
* @author lin
* @date 2022-04-20 15:21
*/
//开启属性绑定配置功能,CacheProperties类只用了 @ConfigurationProperties注解,没有用@Component将该类注册到容器里,这样无法获得配置信息转化成的bean
//@EnableConfigurationProperties注解,根据意思-开启配置属性,就是使@ConfigurationProperties注解生效,把使用该注解的类进行一次注入
@EnableConfigurationProperties(value = CacheProperties.class)
@Configuration //配置类
@EnableCaching //开启注解
public class MyCacheConfig {
@Bean
RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class)));
config= config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
/**
* GenericFastJsonRedisSerializer fastjson家族的
* GenericJackson2JsonRedisSerializer spring自带的 package org.springframework.data.redis.serializer;
*/
//指定序列化-Jackson
config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
//指定序列化-fastjson
//config= config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));
//从所有配置中取出redis的配置
CacheProperties.Redis redisProperties = cacheProperties.getRedis();
//将配置文件中所有的配置都生效(直接从源码里面拷 RedisCacheConfiguration)
if (redisProperties.getTimeToLive() != null) {
config = config.entryTtl(redisProperties.getTimeToLive());
}
if (redisProperties.getKeyPrefix() != null) {
config = config.prefixKeysWith(redisProperties.getKeyPrefix());
}
if (!redisProperties.isCacheNullValues()) {
config = config.disableCachingNullValues();
}
if (!redisProperties.isUseKeyPrefix()) {
config = config.disableKeyPrefix();
}
return config;
}
}
@ConfigurationProperties(
prefix = "spring.cache"
)
public class CacheProperties {
private CacheType type;
private List<String> cacheNames = new ArrayList();
private final CacheProperties.Caffeine caffeine = new CacheProperties.Caffeine();
private final CacheProperties.Couchbase couchbase = new CacheProperties.Couchbase();
private final CacheProperties.EhCache ehcache = new CacheProperties.EhCache();
private final CacheProperties.Infinispan infinispan = new CacheProperties.Infinispan();
private final CacheProperties.JCache jcache = new CacheProperties.JCache();
private final CacheProperties.Redis redis = new CacheProperties.Redis();
public CacheProperties() {
}
326

被折叠的 条评论
为什么被折叠?



