最简单的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