SpringBoot自定义starter及自动配置
自动化配置需满足以下条件:
- 根据条件检查classpath下对应的类,就是说需要提供对应可检查的类;
- 当满足条件时能够生成定义的Bean,并注册到容器中去;
- 能够自动配置项目所需要的配置;
在pom.xml中引入SpringBoot自动化配置依赖spring-boot-autoconfigure:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
定义Service服务类,有两个作用,一个为引入的项目提供功能,另外一个用来springboot自动配置时的判断依据。
package com.smart.msg; public class MsgService { /** * 访问发送短信的url地址 */ private String url; /** * 短信服务商提供的请求keyId */ private String accessKeyId; /** * 短信服务商提供的KeySecret */ private String accessKeySecret; public MsgService(String url, String accessKeyId, String accessKeySecret) { this.url = url; this.accessKeyId = accessKeyId; this.accessKeySecret = accessKeySecret; } public int sendMsg(String msg) { // 调用http服务并发送消息,返回结果 return HttpClientUtils.sendMsg(url, accessKeyId, accessKeySecret, msg); } }
定义配置类
定义MsgProperties配置类,用于封装application.properties或application.yml中的基础配置。关于短信发送的配置前缀统一采用msg。通过@ConfigurationProperties注解来进行对应的属性的装配。
@ConfigurationProperties(prefix = "msg") public class MsgProperties { /** * 访问发送短信的url地址 */ private String url; /** * 短信服务商提供的请求keyId */ private String accessKeyId; /** * 短信服务商提供的KeySecret */ private String accessKeySecret; }
创建自动化配置类
自动配置类最核心的当然是@Configuration注解。
@Configuration @ConditionalOnClass(MsgService.class) @EnableConfigurationProperties(MsgProperties.class) public class MsgAutoConfiguration { /** * 注入属性配置类 */ @Resource private MsgProperties msgProperties; @Bean @ConditionalOnMissingBean(MsgService.class) @ConditionalOnProperty(prefix = "msg", value = "enabled", havingValue = "true") public MsgService msgService() { MsgService msgService = new MsgService(msgProperties.getUrl(), msgProperties.getAccessKeyId(),msgProperties.getAccessKeySecret()); // 如果提供了其他set方法,在此也可以调用对应方法对其进行相应的设置或初始化。 return msgService; } }
添加spring.factories
当所有的基础代码和自动配置类都准备完成,就需要对其进行注册。也就是熟悉的META-INF/spring.factories配置文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.smart.msg.MsgAutoConfiguration
在spring.factories配置文件中注册MsgAutoConfiguration类。如果有多个自动配置类,用逗号分隔换行即可。
在其他项目中,通过以下依赖引入该依赖。
<dependency> <groupId>com.secbro2</groupId> <artifactId>spring-boot-starter-msg</artifactId> <version>1.0-SNAPSHOT</version> </dependency>
在当前项目的application.properties中配置对应的参数:
msg.enabled=true
msg.url=127.0.0.1
msg.accessKeyId=10001
msg.accessKeySecret=afelwjfwfwef
立志如山 静心求实
浙公网安备 33010602011771号