自定义springboot启动器

场景:

当需要把一些公用的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>

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值