springboot-自定义starter

目录

一,简介

1.1 启动器starter命名

1.2 什么是SpringBoot starter机制

1.3 为什么要自定义starter

1.4 什么时候需要创建自定义starter

 自动加载核心注解说明

 二,sms短信启动器starter制作

自定义starter的开发流程

1.1 创建Starter项目

 2.编写相关属性类:SmsProperties.java

3.编写Starter项目的业务功能

4.编写自动配置类SmsAutoConfig.java

5.编写spring.factories文件加载自动配置类

6.打包安装

7.其它项目引用

 成功

 三.自定义starterAOP日志模块

自定义starter的开发流程

 1.创建Starter项目

 2.编写相关属性类:WebLogProperties.java

3.编写Starter项目的业务功能

4.编写自动配置类WebLogConfig.java

5.编写spring.factories文件加载自动配置类

6.打包安装

7.其它项目引用


一,简介

1.1 启动器starter命名

#官方
spring-boot-starter-jdbc
spring-boot-starter-web
spring-boot-starter-freemarker
#第三方
sms-spring-boot-starter
myLog-spring-boot-starter

1.2 什么是SpringBoot starter机制

SpringBoot中的starter是一种非常重要的机制(自动化配置),能够抛弃以前繁杂的配置,将其统一集成进starter,
应用者只需要在maven中引入starter依赖,SpringBoot就能自动扫描到要加载的信息并启动相应的默认配置。
starter让我们摆脱了各种依赖库的处理,需要配置各种信息的困扰。SpringBoot会自动通过classpath路径下的类发现需要的Bean,
并注册进IOC容器。SpringBoot提供了针对日常企业应用研发各种场景的spring-boot-starter依赖模块。
所有这些依赖模块都遵循着约定成俗的默认配置,并允许我们调整这些配置,即遵循“约定大于配置”的理念。

1.3 为什么要自定义starter

在我们的日常开发工作中,经常会有一些独立于业务之外的配置模块,我们经常将其放到一个特定的包下,
然后如果另一个工程需要复用这块功能的时候,需要将代码硬拷贝到另一个工程,重新集成一遍,麻烦至极。
如果我们将这些可独立于业务代码之外的功能配置模块封装成一个个starter,复用的时候只需要将其在pom中引用依赖即可,
SpringBoot为我们完成自动装配,简直不要太爽

1.4 什么时候需要创建自定义starter

在我们的日常开发工作中,可能会需要开发一个通用模块,以供其它工程复用。SpringBoot就为我们提供这样的功能机制,
我们可以把我们的通用模块封装成一个个starter,这样其它工程复用的时候只需要在pom中引用依赖即可,
由SpringBoot为我们完成自动装配。

常见场景:
1.通用模块-短信发送模块
2.基于AOP技术实现日志切面 
3.分布式雪花ID,Long-->string,解决精度问题
jackson2/fastjson
4.微服务项目的数据库连接池配置
5.微服务项目的每个模块都要访问redis数据库,每个模块都要配置redisTemplate
也可以通过starter解决

 自动加载核心注解说明

个性化加载配置

 二,sms短信启动器starter制作

自定义starter的开发流程

1.创建Starter项目(spring-initl 2.1.14)
2.定义Starter需要的配置类(Properties)
3.编写Starter项目的业务功能
4.编写自动配置类
5.编写spring.factories文件加载自动配置类
6.打包安装
7.其它项目引用

1.1 创建Starter项目

1.命名规范
   SpringBoot官方命名方式
   格式:spring-boot-starter-{模块名}
   举例:spring-boot-starter-web
   自定义命名方式
   格式:{模块名}-spring-boot-starter
   举例:mystarter-spring-boot-starter

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>
        </dependencies>

 2.编写相关属性类:SmsProperties.java

package com.ljj.smsspringbootstarter.properties;

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

/**
 * @author ljj
 * @site www.xiaomage.com
 * @company
 * @create  2022-11-25 16:48
 *
 * 短信发送时,一般要提供短信账户凭证
 * spring:
 *     application:
 *         name: sms-spring-boot-starter
 *         当需要使用自定义sms的模块时 在yml文件中进行配置
 * spring:
 *     application:
 *         name: sms-spring-boot-starter
 *
 * ConfigurationProperties 默认时会报错的 然后需要在starter项目配置类中进行解决
 *
 */
@ConfigurationProperties(prefix = "spboot.sms")
public class SmsProperties {

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

}

3.编写Starter项目的业务功能

SmsService.java

package com.ljj.smsspringbootstarter.service;

/**
 * @author小李飞刀
 * @site www.javaxl.com
 */
public interface SmsService {
    /**
     * 发送短信
     *
     * @param phone        要发送的手机号
     * @param signName     短信签名-在短信控制台中找
     * @param templateCode 短信模板-在短信控制台中找
     * @param data         要发送的内容
     */
    void send(String phone, String signName, String templateCode, String data);
}

 SmsServiceImpl.java

模拟阿里短信接口

package com.ljj.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);
    }
}

4.编写自动配置类SmsAutoConfig.java

package com.ljj.smsspringbootstarter.config;

import com.ljj.smsspringbootstarter.properties.SmsProperties;
import com.ljj.smsspringbootstarter.service.SmsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author ljj
 * @site www.xiaomage.com
 * @company
 * @create  2022-11-25 17:19
 * 
 * 1. @Configuration:
 *    定义一个配置类
 * 2. @EnableConfigurationProperties:
 *    @EnableConfigurationProperties注解的作用是@ConfigurationProperties注解生效。
 *    如果只配置@ConfigurationProperties注解,在IOC容器中是获取不到properties配置文件转化的bean的
 */
@Configuration
@EnableConfigurationProperties
public class SmsAutConfig {
    @Autowired
    private SmsProperties smsProperties;
//将短信发送的业务类交给spring容器进行管理
    @Bean
    public SmsServiceImpl smsService(){
        return new SmsServiceImpl(smsProperties.getAccessKeyId(),smsProperties.getAccessKeySecret());
    }
}

5.编写spring.factories文件加载自动配置类

1.在resources下新建META-INF文件夹,然后创建spring.factories文件
2.在该文件中加入如下配置,该配置指定上步骤中定义的配置类为自动装配的配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.ljj.smspringbootstater.config.SmsAutConfig

注1:其中AutoConfig是starter配置文件的类限定名,多个之间逗号分割,还可以\进行转义即相当于去掉后面换行和空格符号  

# Auto Configure
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    com.baomidou.mybatisplus.autoconfigure.MybatisPlusLanguageDriverAutoConfiguration,\
    com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration 

 spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.ljj.smsspringbootstarter.config.SmsAutConfig

6.打包安装

打包时需要注意一下,SpringBoot项目打包的JAR是可执行JAR,它的类放在BOOT-INF目录下,
如果直接作为其他项目的依赖,会找不到类。可以通过修改pom文件来解决,代码如下:

<packaging>jar</packaging>

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <classifier>exec</classifier>
    </configuration>

点击打包

 ​​​​​​在本地仓库中可以找到

7.其它项目引用

#构建项目测试用的spboot项目,勾选组件lombok以及spring-boot-starter-web
#添加自定义starter依赖如下

<dependency>
    <groupId>com.ljj</groupId>
    <artifactId>sms-spring-boot-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

application.yml

server:
    port: 8080
spring:
    application:
        name: testsmsspboot
spcloud:
    sms:
        access-key-id: xaioli
        access-key-secret: 123456

 SmsController.java

package com.ljj.spbootxy.controller;

import com.ljj.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","签名","336600","你好,短信启动器创建成功!!");
        return "success";
    }
}

 成功

 

 三.自定义starterAOP日志模块

自定义starter的开发流程

1.创建Starter项目(spring-initl 2.1.14)
2.定义Starter需要的配置类(Properties)
3.编写Starter项目的业务功能
4.编写自动配置类
5.编写spring.factories文件加载自动配置类
6.打包安装
7.其它项目引用

 1.创建Starter项目

1.命名规范
   SpringBoot官方命名方式
   格式:spring-boot-starter-{模块名}
   举例:spring-boot-starter-web
   自定义命名方式
   格式:{模块名}-spring-boot-starter
   举例:mystarter-spring-boot-starter
   
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>   

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

 2.编写相关属性类:WebLogProperties.java

package com.ljj.mylogspringbootstarter.properties;

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

@ConfigurationProperties(prefix = "spboot.mylog")
public class MyLogProperties {
    private boolean enabled;

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
}

3.编写Starter项目的业务功能

WebLogAspect.java

package com.ljj.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;

// servlet -> springmvc -> spring-boot-starter-web
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);
    }
}

4.编写自动配置类WebLogConfig.java

1. @Configuration:
   定义一个配置类
2. @EnableConfigurationProperties:
   @EnableConfigurationProperties注解的作用是@ConfigurationProperties注解生效。
   如果只配置@ConfigurationProperties注解,在IOC容器中是获取不到properties配置文件转化的bean的

package com.ljj.weblogspringbootstarter.config;

import com.ljj.weblogspringbootstarter.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();
    }
}

5.编写spring.factories文件加载自动配置类

1.在resources下新建META-INF文件夹,然后创建spring.factories文件
2.在该文件中加入如下配置,该配置指定上步骤中定义的配置类为自动装配的配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.ljj.zzcloudspringbootstarter.config.AutoConfig

注1:其中AutoConfig是starter配置文件的类限定名,多个之间逗号分割,还可以\进行转义即相当于去掉后面换行和空格符号  
    # Auto Configure
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    com.baomidou.mybatisplus.autoconfigure.MybatisPlusLanguageDriverAutoConfiguration,\
    com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration 

 spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.ljj.mylogspringbootstarter.config.MyLogAutoConfig

6.打包安装

打包时需要注意一下,SpringBoot项目打包的JAR是可执行JAR,它的类放在BOOT-INF目录下,
如果直接作为其他项目的依赖,会找不到类。可以通过修改pom文件来解决,代码如下:

<packaging>jar</packaging>

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <classifier>exec</classifier>
    </configuration>
</plugin> 

 7.其它项目引用

#构建项目测试用的spboot项目,勾选组件lombok以及spring-boot-starter-web
#添加自定义starter依赖如下

<dependency>
    <groupId>com.ljj</groupId>
    <artifactId>mylog-spring-boot-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

 application.yml

server:
    port: 8080
spring:
    application:
        name: testsmsspboot
spcloud:
    sms:
        access-key-id: ljj
        access-key-secret: 123456
    mylog:
        enabled: true

SmsController.java  

package com.ljj.spbootxy.controller;

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 SnsService smsService;
    @RequestMapping("/sms")
    public String sendSms(){
        smsService.send("15970290566","签名","1000","你好自定义短信发送starter");
        return "success";
    }
}

访问

http://localhost:8080/sms

测试结果如下

 大概逻辑图,有点潦草哈

注: 就算把自定义的启动器的项目给删除掉了  只要本地仓库中存有jar包,依然不影响在其他项目中使用

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
自定义Spring Boot Starter是一种用于简化Spring Boot应用程序配置和依赖管理的机制。它由几个组件组成,包括starter包、autoconfiguration包和配置文件。 首先,你需要创建一个Maven工程,并创建三个模块。其中,starter包负责引入依赖,autoconfiguration包负责实现装配。在autoconfiguration包中,你需要定义对应的properties类、configuration类和核心业务类。此外,你还需要在autoconfiguration包的/resources/META-INF/目录下添加spring.factories文件,并配置org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.qiejk.demo.springboot.autoconfiguration.DemoAutoConfiguration。这一步是Spring Boot装配的核心,只有添加了这个内容,Spring Boot才会进行自动装配。\[1\] 在父模块的pom文件中,你需要引入Spring Boot的依赖,例如spring-boot-starter-web,以及指定Spring Boot的版本。这样,你的自定义starter模块就可以基于Spring Boot进行开发和使用。\[2\] 最后,你需要创建一个配置文件,用于告诉Spring Boot在启动时扫描该配置文件,并将其中的配置类加载到Spring容器中。这个配置文件的作用是指定自动配置类的位置。\[3\] 通过以上步骤,你就可以创建自定义Spring Boot Starter,并在应用程序中使用它来简化配置和依赖管理。 #### 引用[.reference_title] - *1* [如何自定义springboot-starter](https://blog.csdn.net/sinat_29434159/article/details/123995794)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [SpringBoot自定义Starter篇](https://blog.csdn.net/m0_46571920/article/details/122910726)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值