000000 提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
自定义starter
1.starter简介
#官方
spring-boot-starter-jdbc
spring-boot-starter-web
spring-boot-starter-freemarker
#第三方
sms-spring-boot-starter
myLog-spring-boot-starter
1.1什么是SpringBoot starter机制
SpringBoot中的starter是一种非常重要的机制(自动化配置),能够抛弃以前繁杂的配置,将其统一集成进starter,
应用者只需要在maven中引入starter依赖,SpringBoot就能自动扫描到要加载的信息并启动相应的默认配置。
starter让我们摆脱了各种依赖库的处理,需要配置各种信息的困扰。SpringBoot会自动通过classpath路径下的类发现需要的Bean,
并注册进IOC容器。SpringBoot提供了针对日常企业应用研发各种场景的spring-boot-starter依赖模块。
所有这些依赖模块都遵循着约定成俗的默认配置,并允许我们调整这些配置,即遵循“约定大于配置”的理念。
1.2为什么要自定义starter
在我们的日常开发工作中,经常会有一些独立于业务之外的配置模块,我们经常将其放到一个特定的包下,
然后如果另一个工程需要复用这块功能的时候,需要将代码硬拷贝到另一个工程,重新集成一遍,麻烦至极。
如果我们将这些可独立于业务代码之外的功能配置模块封装成一个个starter,复用的时候只需要将其在pom中引用依赖即可,
SpringBoot为我们完成自动装配,简直不要太爽
1.3什么时候需要创建自定义starter
在我们的日常开发工作中,可能会需要开发一个通用模块,以供其它工程复用。SpringBoot就为我们提供这样的功能机制,
我们可以把我们的通用模块封装成一个个starter,这样其它工程复用的时候只需要在pom中引用依赖即可,
由SpringBoot为我们完成自动装配。常见场景:
1.通用模块-短信发送模块
2.基于AOP技术实现日志切面
3.分布式雪花ID,Long–>string,解决精度问题 jackson2/fastjson
4.微服务项目的数据库连接池配置
5.微服务项目的每个模块都要访问redis数据库,每个模块都要配置redisTemplate 也可以通过starter解决
1.4自动加载核心注解说明
2.短信发送starter
2.1创建sms-spring-boot-starter项目
命名规范
SpringBoot官方命名方式
格式:spring-boot-starter-{模块名}
举例:spring-boot-starter-web
自定义命名方式
格式:{模块名}-spring-boot-starter
举例:mystarter-spring-boot-starter
2.2必须引入的依赖
<!--表示两个项目之间依赖不传递;不设置optional或者optional是false,表示传递依赖-->
<!--例如:project1依赖a.jar(optional=true),project2依赖project1,则project2不依赖a.jar-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2.3在properties中添加SmsProperties
package com.zking.smsspringbootstarter.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "spcloud.sms")
public class SmsProperties {
//访问ID及账号
private String accessKeyId;
//访问凭证及密码
private String accessKeySecret;
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
}
2.4.1在service中添加SmsService
package com.zking.smsspringbootstarter.service;
public interface SmsService {
/**
* 发送短信
*
* @param phone 要发送的手机号
* @param signName 短信签名-在短信控制台中找
* @param templateCode 短信模板-在短信控制台中找
* @param data 要发送的内容
*/
void send(String phone, String signName, String templateCode, String data);
}
2.4.2在service下添加impl方法实现类SmsServiceImpl
package com.zking.smsspringbootstarter.service;
public class SmsServiceImpl implements SmsService {
private String accessKeyId;//访问ID、即帐号
private String accessKeySecret;//访问凭证,即密码
public SmsServiceImpl(String accessKeyId, String accessKeySecret) {
this.accessKeyId = accessKeyId;
this.accessKeySecret = accessKeySecret;
}
@Override
public void send(String phone, String signName, String templateCode, String data) {
System.out.println("接入短信系统,accessKeyId=" + accessKeyId + ",accessKeySecret=" + accessKeySecret);
System.out.println("短信发送,phone=" + phone + ",signName=" + signName + ",templateCode=" + templateCode + ",data=" + data);
}
}
2.5在config中编写自动配置类SmsAutoConfig.java
package com.zking.smsspringbootstarter.config;
import com.zking.smsspringbootstarter.properties.SmsProperties;
import com.zking.smsspringbootstarter.service.SmsService;
import com.zking.smsspringbootstarter.service.SmsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties({SmsProperties.class})
public class SmsAutoConfig {
@Autowired
private SmsProperties smsProperties;
@Bean
public SmsService smsService(){
return new SmsServiceImpl(smsProperties.getAccessKeyId(),
smsProperties.getAccessKeySecret());
}
}
2.6编写spring.factories文件加载自动配置类
在resources下新建META-INF文件夹,然后创建spring.factories文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.zking.smsspringbootstarter.config.SmsAutoConfig
2.7打包安装
打包时需要注意一下,SpringBoot项目打包的JAR是可执行JAR,它的类放在BOOT-INF目录下,
如果直接作为其他项目的依赖,会找不到类。可以通过修改pom文件来解决,代码如下:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>exec</classifier>
</configuration>
</plugin>
在pom.xml中找到
<description>sms-spring-boot-starter</description>
添加
<packaging>jar</packaging>
打包到本地成jar包
运行结果:
发现本地成功生成jar包文件
2.8测试:其它项目引用
在其他项目中的pom.xml中导入
<dependency>
<groupId>com.zking</groupId>
<artifactId>sms-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
修改application.yml
spcloud:
sms:
access-key-id: 123456
access-key-secret: lczlcz
添加SmsController.java
package com.zking.spboot04.web;
import com.zking.smsspringbootstarter.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SmsController {
@Autowired
private SmsService smsService;
@RequestMapping("/sms")
public String sendSms(){
smsService.send("15970290566","签名","1000","你好自定义短信发送starter");
return "success";
}
}
2.9启动项目:
访问 http://localhost:8082//spboot04/sms
将idea中的sms-spring-boot-starter模板删除再重新启动
再次访问
3.日志starter
3.1创建mylog-spring-boot-starter项目
3.2必须引入的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3.3在properties中添加WebLogProperties
package com.zking.weblogspringbootstarter.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "spcloud.weblog")
public class WebLogProperties {
private boolean enabled;
public WebLogProperties() {
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
3.4在aop中添加WebLogAspect
package com.zking.mylogspringbootstarter.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
@Aspect
@Component
@Slf4j
public class WebLogAspect {
//@Pointcut("execution(public * com.zking..controller.*.*(..))")
@Pointcut("execution(* *..*Controller.*(..))")
public void webLog(){}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 记录下请求内容
log.info("开始服务:{}", request.getRequestURL().toString());
log.info("客户端IP :{}" , request.getRemoteAddr());
log.info("参数值 :{}", Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
log.info("返回值 : {}" , ret);
}
}
3.5在config中添加WebLogConfig
package com.zking.mylogspringbootstarter.config;
import com.zking.mylogspringbootstarter.aop.WebLogAspect;
import com.zking.mylogspringbootstarter.properties.WebLogProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @ConditionalOnProperty
* 配置属性a:
* 1:不配置a matchifmissing=false 不满足 matchifmissing=true 满足
* 2:配置a=false matchifmissing=false 不满足 matchifmissing=true 不满足
* 3:配置a=true matchifmissing=false 满足 matchifmissing=true 满足
*/
@Configuration
@EnableConfigurationProperties({WebLogProperties.class})
@ConditionalOnProperty(prefix = "spcloud.weblog",
value = "enabled")
public class WebLogConfig {
@Bean
@ConditionalOnMissingBean
public WebLogAspect webLogAspect(){
return new WebLogAspect();
}
}
3.6编写spring.factories文件加载自动配置类
在resources下新建META-INF文件夹,然后创建spring.factories文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.zking.mylogspringbootstarter.config.WebLogConfig
3.7打包安装
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>exec</classifier>
</configuration>
</plugin>
<packaging>jar</packaging>
运行结果:
3.8在其它项目中引用
修改pom.xml
<dependency>
<groupId>com.zking</groupId>
<artifactId>mylog-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
在application.yml添加
spcloud:
sms:
access-key-id: 123456
access-key-secret: xiaoli
weblog:
enabled: true
运行结果:
将idea中的mylog-spring-boot-starter删除后重启项目
运行结果;