自定义Spring Boot Starter

自定义Spring Boot Starter

  1. pom中添加依赖
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
    </dependencies>
  1. 编写配置类:
@Configuration
@EnableConfigurationProperties(JedisProperties.class)
@ConditionalOnClass(Jedis.class)
public class JedisAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public Jedis jedis(JedisProperties jedisProperties) {
        Jedis jedis = new Jedis(jedisProperties.getHost(), jedisProperties.getPort());
        jedis.auth(jedisProperties.getPassword());
        System.out.println("jedis-----------init");
        return jedis;
    }
}
  1. 编写属性文件配置类:
@ConfigurationProperties(prefix = "redis")
public class JedisProperties {
    private String host;
    private Integer port;
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getHost() {
        return host;
    }

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

    public Integer getPort() {
        return port;
    }

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

}
  1. META-INF/spring.properties 中添加配置,或者使用@Impoert注解导入
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.aimilin.JedisAutoConfiguration
  1. 使用:pom导入依赖:
<dependency>
    <groupId>com.aimilin</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
    <version>1.0.0</version>
</dependency>
@Component
public class RedisTest {
    @Autowired
    private Jedis jedis;

    public void run() {
        jedis.set("hello", "text");
        System.out.println("redis ---- text");
    }
}

猜你喜欢

转载自blog.csdn.net/afgasdg/article/details/79758619