手写Jedis加入springboot自动配置,可在yml中配置属性
传送门:(手写简易版Jedis)
前面手写实现了简单的Jedis客户端,那么有点好奇,springboot是如何自动整合了redistemplate,实现了自动配置的呢?
我们是否可以将自己手写的Jedis,添加到springboot的自动配置里面去呢?
并且可以在yml中配置需要输入的配置呢?
好的,去实现了一遍,看代码:
将手写的Jedis利用注解的形式注册到spring容器:
/**
*
* @author An
*
*/
@Configuration
public class Config {
@Bean
public TestJedis TestJedis() {
return new TestJedis("*.*.*.*", 6379);
}
}
没错就这么简单。
那么如果我们想要向springboot自动配置的方式,有默认值,并且可以在yml中可以随时更改值那该怎么做呢?
我们就不在/META-INF/spring.factories文件里面去添加对应的autoconfig了
直接用配置类的方式,不那么麻烦。
上代码:
@Configuration
@EnableConfigurationProperties(TestJedisProperties.class)
public class Service {
private final TestJedisProperties properties;
public Service(TestJedisProperties properties) {
this.properties = properties;
}
@Bean
public com.lg.nw.TestJedis TestJedis() {
return new com.lg.nw.TestJedis(properties.getHost(), properties.getProt());
}
}
属性绑定类
/**
*
* @author An
* 属性绑定类
*/
@ConfigurationProperties(prefix = "spring.jedis")
public class TestJedisProperties {
private String host;
private int prot;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getProt() {
return prot;
}
public void setProt(int prot) {
this.prot = prot;
}
}
好了,代码编写完成,很多判定的注解也不加了,什么类存在不存在,都不管了。
我们来测试一下。
看清楚哦,这个是自定义的spring.jedis哦,随便设置成什么样子都可以哦
到了这里就全部搞定啦~~~自己的第三方也就和springboot自动配置初步的配置完成了。