@Data
//@ConfigurationProperties的大致作用就是通过它可以把properties或者yml配置直接转成对象
@ConfigurationProperties(prefix = JedisProperties.JEDIS_PREFIX)
//对 redis 配置参数进行读取和绑定,配置属性注入到 JedisProperties
public class JedisProperties {
//这里也可以不选择配置一个常量,@ConfigurationProperties(prefix = jedis) 即可
public static final String JEDIS_PREFIX = "jedis";
private String host;
private int port;
private int maxTotal;
private int maxIdle;
private int maxWaitMillis;
}
5.添加Jedis配置类
//配置了 Redis 连接池之后,将 Redis 连接池 注入到 RedisClient 中,并生成 RedisClient Bean
@Configuration
@EnableConfigurationProperties(JedisProperties.class)//开启属性注入,通过@autowired注入
@ConditionalOnClass(RedisClient.class)//判断这个类是否在classpath中存在
public class JedisAutoConfiguration {
@Autowired
private JedisProperties prop;
@Bean(name="jedisPool")
public JedisPool jedisPool() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(prop.getMaxTotal());
config.setMaxIdle(prop.getMaxIdle());
config.setMaxWaitMillis(prop.getMaxWaitMillis());
return new JedisPool(config, prop.getHost(), prop.getPort());
}
@Bean
@ConditionalOnMissingBean(RedisClient.class)//容器中如果没有RedisClient这个类,那么自动配置这个RedisClient
//这个注解可以使用在字段和参数上,默认使用为空(这个注解要和@AutoWired一起使用,否则无法注入)
//@Autowired默认是根据类型进行注入的,因此如果有多个类型一样的Bean候选者,则需要限定其中一个候选者,否则将抛出异常
//@Qualifier限定描述符除了能根据名字进行注入,更能进行更细粒度的控制如何选择候选者
public RedisClient redisClient(@Qualifier("jedisPool")JedisPool pool) {
RedisClient redisClient = new RedisClient();
redisClient.setJedisPool(pool);
return redisClient;
}
}