SpringBoot中实现自定义start
本文主要通过模拟实现redis的功能来自定义start,具体实现口可以往下看
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
@ConfigurationProperties(prefix = "forlan.redis")
public class ForlanRedisProperties {
private int database = 0;
private String host = "localhost";
private String password;
private int port = 6379;
public int getDatabase() {
return database;
}
public void setDatabase(int database) {
this.database = database;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
@Configuration
@ConditionalOnClass(value = Jedis.class)
@EnableConfigurationProperties(ForlanRedisProperties.class)
public class ForlanAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public Jedis jedis(ForlanRedisProperties forlanRedisProperties) {
Jedis jedis = new Jedis(forlanRedisProperties.getHost(), forlanRedisProperties.getPort());
if (StringUtils.isNotBlank(forlanRedisProperties.getPassword())) {
jedis.auth(forlanRedisProperties.getPassword());
}
jedis.select(forlanRedisProperties.getDatabase());
return jedis;
}
}
在resources目录META-INF新建
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.forlan.spring.autoconfigure.ForlanAutoConfiguration
引入自定义start
<dependencies>
<!--自定义start-->
<dependency>
<groupId>cn.forlan</groupId>
<artifactId>forlan-redis-start</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
配置属性文件
#forlan_redis
forlan.redis.database=1
forlan.redis.host=127.0.0.1
forlan.redis.password=
forlan.redis.port=6379
测试方法
@Autowired
private Jedis jedis;
@Test
public void testRedis() {
jedis.set("forlan-redis-start", "测试自定义组件");
}
查看redis,发现forlan-redis-start已经缓存到redis,自定义start正常使用
本地:1>get forlan-redis-start
"测试自定义组件"