018-Spring Boot Starter开发
自建spring-boot-starter
artifactId命名
Spring 官方 Starter通常命名为spring-boot-starter-{name}如 spring-boot-starter-web,
Spring官方建议非官方Starter命名应遵循{name}-spring-boot-starter的格式。
示例以redis为例
1》新建一个maven项目redis-spring-boot-starter,添加pom
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>1.5.9.RELEASE</version> </dependency>
2》添加配置属性
package com.lhx.spring.redis; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "redis") public class RedisProperties { private String host; private Integer port; 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; } }
3》添加AutoConfiguration类
@Configuration @ConditionalOnClass(Jedis.class) @EnableConfigurationProperties(RedisProperties.class) public class RedisAutoConfiguration { @Bean @ConditionalOnMissingBean(Jedis.class) public Jedis jedis(RedisProperties redisProperties) { return new Jedis(redisProperties.getHost(), redisProperties.getPort().intValue()); } }
此时程序使用。
4》程序使用
添加依赖包
<dependency> <groupId>com.lhx.spring</groupId> <artifactId>redis-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency>
具体分为两种:
方式一、在redis-spring-boot-starter添加注解方式,Import导入配置类
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import(RedisAutoConfiguration.class) public @interface EnableRedis { }
程序使用
@EnableRedis @SpringBootApplication public class App { public static void main(String[] args) throws SQLException { ConfigurableApplicationContext context = SpringApplication.run(App.class, args); Jedis jedis = context.getBean(Jedis.class); jedis.set("id","3333"); System.out.println(jedis.get("id")); context.close(); } }
方式二、spring.factories,配置配置类
查看在spring-boot-autoconfigure-1.5.9.RELEASE.jar包中META-INF下的spring.factories文件
一般都是在starter
项目的resources/META-INF
文件夹下的spring.factories文件中加入需要自动化配置类的全限定名称。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.lhx.spring.redis.RedisAutoConfiguration
spring boot项目中的EnableAutoConfigurationImportSelector会自动去每个jar的相应文件下查看spring.factories文件内容,并将其中的类加载出来在auto-configuration过程中进行配置。而EnableAutoConfigurationImportSelector在@EnableAutoConfiguration注解中被import。
程序使用
@SpringBootApplication public class App { public static void main(String[] args) throws SQLException { ConfigurableApplicationContext context = SpringApplication.run(App.class, args); Jedis jedis = context.getBean(Jedis.class); jedis.set("id","4444"); System.out.println(jedis.get("id")); context.close(); } }