一、Spring Boot Starter 概述
1.1 什么是 Starter
Spring Boot Starter 是一种特殊的依赖管理机制,它:
- 聚合相关依赖:将多个相关的依赖打包在一起
- 自动配置:基于条件判断自动配置组件
- 简化集成:提供开箱即用的功能
1.2 自定义 Starter 的价值
- 封装公司内部通用功能
- 提供标准化的集成方式
- 减少重复配置工作
二、创建 Redis Cache Starter
2.1 项目结构
redis-cache-starter/
├── pom.xml
└── src/main/java/com/example/starter/
├── RedisCacheAutoConfiguration.java
├── RedisCacheProperties.java
└── annotation/EnableRedisCache.java
2.2 POM 依赖配置
xml
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- Spring Boot Configuration Processor -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- Jedis Client -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!-- Spring Data Redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
</dependencies>
2.3 配置属性类
java
@Component
@ConfigurationProperties(prefix = "redis.cache")
public class RedisCacheProperties {
private String host = "localhost";
private int port = 6379;
private String password = "";
private int database = 0;
private int timeout = 2000;
private int maxTotal = 8;
private int maxIdle = 8;
private int minIdle = 0;
private boolean enabled = true;
// getters and setters...
}
2.4 自动配置类
java
@Configuration
@EnableConfigurationProperties(RedisCacheProperties.class)
@ConditionalOnProperty(prefix = "redis.cache", name = "enabled", havingValue = "true", matchIfMissing = true)
public class RedisCacheAutoConfiguration {
@Autowired
private RedisCacheProperties properties;
@Bean
public JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(properties.getMaxTotal());
config.setMaxIdle(properties.getMaxIdle());
config.setMinIdle(properties.getMinIdle());
return config;
}
@Bean
public RedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory(jedisPoolConfig());
factory.setHostName(properties.getHost());
factory.setPort(properties.getPort());
if (properties.getPassword() != null && !properties.getPassword().isEmpty()) {
factory.setPassword(properties.getPassword());
}
factory.setDatabase(properties.getDatabase());
factory.setTimeout(properties.getTimeout());
factory.afterPropertiesSet();
return factory;
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
2.5 配置文件注册
在/resources/下新建配置文件 /META-INF/spring.factories 中:
properties
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.starter.RedisCacheAutoConfiguration
三、在新项目中使用 Starter
3.1 新项目 POM 配置
xml
<dependency>
<groupId>com.example</groupId>
<artifactId>redis-cache-starter</artifactId>
<version>1.0.0</version>
</dependency>
3.3 配置文件设置
yaml
redis:
cache:
host: localhost
port: 6379
database: 0
timeout: 2000
max-total: 8
max-idle: 8
min-idle: 0
enabled: true
3.4 业务代码使用
java
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void setValue(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object getValue(String key) {
return redisTemplate.opsForValue().get(key);
}
}
四、测试验证
4.1 单元测试
java
@SpringBootTest
class RedisStarterTest {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Test
void testRedisConnection() {
String testKey = "test-key";
String testValue = "test-value";
redisTemplate.opsForValue().set(testKey, testValue);
Object retrievedValue = redisTemplate.opsForValue().get(testKey);
assertEquals(testValue, retrievedValue);
}
}
五、最佳实践
5.1 命名规范
- 遵循
*-starter命名规则 - 配置前缀统一管理
5.2 配置灵活性
- 提供合理的默认值
- 支持条件化配置
5.3 错误处理
- 优雅的异常处理
- 清晰的错误信息提示
通过以上步骤,我们可以创建一个功能完整、易于使用的自定义 Starter,大大提高开发效率和代码复用性。