自定义starter

最简单的starter自定义,以创建redis bean为例

1.建立一个maven的父工程

2.创建一个redis-spring-boot-starter、redis-spring-boot-autoconfigure子项目

3.redis-spring-boot-autoconfigure引入依赖

<!--   引入jedis依赖    -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

4.编写一个配置类

package com.liang.redis.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;

/**
 * @author: Xiao Liang Zai
 * @Date: 2021/8/17 15:53
 * @description:
 */
@Configuration
@EnableConfigurationProperties(RedisProperties.class) //确保能被spring所识别
@ConditionalOnClass(Jedis.class) //加限制条件 只有当Jedis.class存在时才会导入
public class RedisAutoConfiguration {
    /**
     * 提供jedis的bean
     */
    @Bean
    @ConditionalOnMissingBean(name = "jedis")
    public Jedis jedis(RedisProperties redis) {
        return new Jedis(redis.getHost(), redis.getPort());
    }
}

配置文件

package com.liang.redis.config;

import org.springframework.boot.context.properties.ConfigurationProperties;


/**
 * @author: Xiao Liang Zai
 * @Date: 2021/8/17 15:55
 * @description:
 */


/**
 *@ConfigurationProperties(prefix = "redis") 与配置文件相绑定 prefix:前缀
 * 在哪个项目中使用就在其yml配置文件中
 * eg:
 * redis.host=192.168.3.181
 * redis.port=6379
 */
@ConfigurationProperties(prefix = "redis")
public class RedisProperties {

    private String host = "localhost";

    private int port = 6379;

    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;
    }
}

      在资源目录下新增resource/META-INF/spring.factories文件

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.liang.redis.config.RedisAutoConfiguration

当springboot项目启动就会去加载bean

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值