场景:
当需要把一些公用的api封装成jar包时,就可以用springboot自定义启动器来做
原理
springboot自定义启动器用到的是springboot中的SPI原理,Sringboot会去加载META-INF/spring.factories配置文件,加载EnableAutoConfiguration 为key的所有类
1、自定义启动器核心工程
spring.factories 配置内容
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.xx.jack.start.CustomStarterRun
被 springboot SPI 加载的类CustomStarterRun
@Configuration
@ConditionalOnClass(CustomTemplate.class)
@EnableConfigurationProperties(RedisConfig.class)
public class CustomStarterRun {
@Autowired
private RedisConfig redisConfig;
@Bean
public CustomTemplate jackTemplate() {
CustomTemplate customTemplate = new CustomTemplate(redisConfig);
return customTemplate;
}
}
这个 CustomTemplate 实例就是我们封装的通用 API,其他工程可以直接导入 jar使用 ,代码如下
public class CustomTemplate<K,V> {
private Jedis jedis;
public CustomTemplate(RedisConfig redisConfig) {
jedis = new Jedis(redisConfig.getHost(),redisConfig.getPort());
}
public String put(K k,V v) {
System.out.println("-------加入缓存------");
System.out.println("key----:"+k);
System.out.println("value----:"+v);
final String keyString = k.toString();
final Object valuef = v;
final long liveTime = 86400;
byte[] keyb = keyString.getBytes();
byte[] valueb = SerializationUtils.serialize((Serializable) valuef);
return jedis.set(keyb,valueb);
}
public Object get(K k) {
final String keyf = k.toString();
byte[] key = keyf.getBytes();
byte[] bytes = jedis.get(key);
return SerializationUtils.deserialize(bytes);
}
}
@Data
@ConfigurationProperties(prefix = "spring.redis")
public class RedisConfig {
private String host;
private Integer port;
}
2、自定义starter
我们还会定义一个没代码的工程,在这个工程里只有一个 pom文件。pom 里面就是对前面核心工程 jar 包的导入
<dependencies>
<dependency>
<groupId>com.xx.xx</groupId>
<artifactId>custom-spring-boot-starter-autoconfigurer</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
3、自定义启动器的使用
其实就只有在 springboot 工程 pom 文件里面导入自定义starter依赖就可以了
<dependency>
<groupId>com.xx.xx</groupId>
<artifactId>customTemplate-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>