@ConditionalOnProperty注解控制配置文件是否生效

时间:2025-04-04 07:08:05

这个注解能够控制某个configuration是否生效。具体操作是通过其两个属性name以及havingValue来实现的,其中name用来从中读取某个属性值,如果该值为空,则返回false;如果值不为空,则将该值与havingValue指定的值进行比较,如果一样则返回true;否则返回false。如果返回值为false,则该configuration不生效;为true则生效。

@Configuration
//如果synchronize在配置文件中并且值为true
@ConditionalOnProperty(name = "synchronize", havingValue = "true")
public class SecondDatasourceConfig {

    @Bean(name = "SecondDataSource")
    @Qualifier("SecondDataSource")
    @ConfigurationProperties(prefix = "")
    public DataSource jwcDataSource() {
        return ().build();
    }
}

@EnableCaching  //启用缓存注解
@Configuration
@ConditionalOnProperty(name = "", havingValue = "true")
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 注入生成key的策略(作用于注解注解缓存)
     */
    @Bean(name = "customKeyGenerator")
    public KeyGenerator keyGenerator() {
        return new RedisCacheKeyGenerator();
    }

    @Primary
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        // 对象的序列化
        <Object> valueSerializationPair
                = (jackson2JsonRedisSerializer());
        // 全局redis缓存过期时间。默认1天
        RedisCacheConfiguration redisCacheConfiguration = ()
                .entryTtl((1))
//                .serializeKeysWith()
                .serializeValuesWith(valueSerializationPair);

        return new RedisCacheManager((factory), redisCacheConfiguration);
    }

    /**
     * RedisTemplate配置
     * @param factory redis链接工厂
     * @return RedisTemplate
     */
    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();

        // 设置序列化,key采用redisSerializer,value采用jackson2JsonRedisSerializer
        (factory);
        (redisSerializer);
        (jackson2JsonRedisSerializer());
        (redisSerializer);
        (jackson2JsonRedisSerializer());
        ();
        return template;
    }


    private Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>();
        (objectMapper());
        return jackson2JsonRedisSerializer;
    }

    private ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        (, );
        (.NON_FINAL);

        // 解决jackson2无法反序列化LocalDateTime的问题
        (SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        (new JavaTimeModule());
        return objectMapper;
    }


}