通过实现redis功能来演示如何自定义start

本文主要通过模拟实现redis的功能来自定义start,具体实现口可以往下看

1、新建SpringBoot项目,引入依赖

org.springframework.boot

spring-boot-autoconfigure

org.springframework.boot

spring-boot-configuration-processor

true

2、定义属性类

@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;

}

}

3、定义配置类(重点)

@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;

}

}

4、定义spring.factories

在resources目录META-INF新建

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\

cn.forlan.spring.autoconfigure.ForlanAutoConfiguration

5、测试

引入自定义start

cn.forlan

forlan-redis-start

1.0-SNAPSHOT

配置属性文件

#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

"测试自定义组件"

查看原文