springboot自定义starter

本文以jedis作为演示

命名规范:
spring官方starter通常命名为spring-boot-starter-{name}, 如:spring-boot-starter-web
spring官方建议非官方starter命名应遵循{name}-spring-boot-starter的格式, 如:mybatis-spring-boot-starter

  1. 创建maven jar工程,引入依赖



    
    4.0.0

    jedis-spring-boot-starter
    demo.springboot
    1.0-SNAPSHOT

    jedis-spring-boot-starter

    
        UTF-8
        1.8
        1.8
    

    
        
        
            org.springframework.boot
            spring-boot-autoconfigure
            2.0.6.RELEASE
        

        
        
            redis.clients
            jedis
            3.0.0
            provided
        
    

  1. 创建一个获取配置文件属性的类
//获取配置文件中的属性
@ConfigurationProperties(prefix = "jedis")
public class JedisProperties {

    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;
    }
}
  1. 创建自动装配bean的配置类
@Configuration
//当类路径下有Jedis依赖时进行配置
@ConditionalOnClass(Jedis.class)
//引入JedisProperties对象
@EnableConfigurationProperties(JedisProperties.class)
public class JedisAutoConfiguration {

    @Bean
    //当spring容器中没有该Bean时注册
    @ConditionalOnMissingBean(Jedis.class)
    public Jedis jedis(JedisProperties jedisProperties){
        //设置地址端口
        Jedis jedis = new Jedis(jedisProperties.getHost(), jedisProperties.getPort());
        //验证密码
        jedis.auth(jedisProperties.getPassword());
        //设置索引库
        jedis.select(jedisProperties.getDatabase());
        jedis.connect();
        return jedis;
    }

}

更多特定注解可从官网或者搜索引擎中搜索

  1. 创建spring.factories
    没有此文件配置,自动配置类不会生效。将创建的配置类路径填写到里面
    此文件需要自己手动创建,位置:src/main/resources/META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=demo.springboot.JedisAutoConfiguration
  1. 打包 mvn install

  2. 创建一个springboot项目测试

    1. application.yml
#不设置配置,默认使用JedisProperties对象的默认值
jedis:
    host: localhost
    port: 6379
    database: 0
    password: root
  1. 测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisApplicationTests {

    @Autowired
    private Jedis jedis;

    @Test
    public void testJedisStarter(){
        jedis.set("test", "hello spring boot starter");
    }

}
  1. 运行完成,查看redis中是否添加了一条数据
localhost:0>get test
"hello spring boot starter"

查到的数据就是测试中添加的数据

项目路径


作者博客

作者公众号


你可能感兴趣的:(springboot自定义starter)