自定义Spring-boot-starter

£可爱£侵袭症+ 提交于 2020-10-19 10:31:47

本文以Jedis举例

pom引入依赖

<groupId>com.bozhon</groupId>
    <artifactId>redis-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>redis-spring-boot-starter</name>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!-- 想要让自定义配置项有提示,导入这个包,在项目编译后会生成元数据,同样是在META-INF目录下-->
        <!-- 会自动生成spring-configuration-metadata.json文件。-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>2.1.1.RELEASE</version>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>

    </dependencies>

JedisProperties

@ConfigurationProperties(prefix = "redis")
public class JedisProperties {

    private String host;

    private int port;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}

JedisAutoConfiguration

@Configuration
@ConditionalOnClass(Jedis.class)
@EnableConfigurationProperties(JedisProperties.class)
public class JedisAutoConfiguration {
    @Bean
    @ConditionalOnMissingBean
    public Jedis jedis(JedisProperties p){
        return new Jedis(p.getHost(),p.getPort());
    }
}

spring.factories

在src/main/resources下增加以下内容

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.bozhon.config.JedisAutoConfiguration

mvn install

使用

引入依赖

<dependency>
            <groupId>com.bozhon</groupId>
            <artifactId>redis-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

增加redis配置

application.properties

redis.host=127.0.0.1
redis.port=6379

Controller编写测试用例

@RestController
public class RedisController {

    @Autowired
    private Jedis jedis;

    @GetMapping("/info")
    public String info() {
        jedis.set("test","11111111");
        return "success";
    }
}

测试

结果显示

依赖文件

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!