企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
`@Conditional`是 Spring 的原生注解,SpringBoot 将它进行扩展,该注解用于做条件判断。 ``` @ConditionalOnXXX:当组件存在时符合条件 @ConditionalOnMissingXXX:当组件不存在时符合条件 ``` 比如 Redis 的自动配置类 RedisAutoConfiguration 就用到了一些条件注解: ```java @AutoConfiguration //当类RedisOperations存在时才注册RedisAutoConfiguration @ConditionalOnClass({RedisOperations.class}) @EnableConfigurationProperties({RedisProperties.class}) @Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class}) public class RedisAutoConfiguration { public RedisAutoConfiguration() { } @Bean //当RedisConnectionDetails还没注册时才注册 @ConditionalOnMissingBean({RedisConnectionDetails.class}) PropertiesRedisConnectionDetails redisConnectionDetails(RedisProperties properties) { return new PropertiesRedisConnectionDetails(properties); } @Bean //当redisTemplate还没注册时才注册 @ConditionalOnMissingBean( name = {"redisTemplate"} ) //当RedisConnectionFactory是单例时才注册 @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); } } ``` 有了条件注解,我们就可以灵活的自定义自动配置类了。自定义自动配置参考章节`Boot[场景启动器]/自定义场景启动器`。