springboot自定义starter

devtools/2024/9/24 6:29:08/

案例1:自定义starter中配置用户信息、接口访问。使用starter时在yml文件配置用户信息

1,创建自定义starter
1.1,创建starter工程xxx-spring-boot-starter并配置pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.2.RELEASE</version><relativePath/></parent><groupId>cn.xxx</groupId><artifactId>xxx-spring-boot-starter</artifactId><version>1.0-SNAPSHOT</version><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency><!--   lombok   --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.6</version></dependency></dependencies>
</project>

1.2,创建配置属性类XXXProperties

/**读取配置文件转换为bean* */
@Data
@ConfigurationProperties(prefix = "xxx")
public class XXXProperties {private String name;private String address;
}

1.3,创建自动配置类XXXServiceAutoConfiguration

@Configuration
//启用配置属性类
@EnableConfigurationProperties(TQProperties.class)
public class TianQingAutoConfiguration {private TQProperties tqProperties;//通过构造方法注入配置属性对象HelloPropertiespublic TianQingAutoConfiguration(TQProperties tqProperties) {this.tqProperties = tqProperties;}//实例化UserInfo并载入Spring IoC容器@Bean@ConditionalOnMissingBeanpublic UserInfo userInfo(){return new UserInfo (tqProperties.getName(),tqProperties.getAddress());}
}

1.4,在resources目录下创建META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.meteorological.config.XXXAutoConfiguration

1.5,创建UserInfo

@Data
public class UserInfo {private String name;private String address;public UserInfo (String name, String address) {this.name = name;this.address = address;}
}

1.6,创建server类

@Service
public class DMService {@Autowiredprivate UserInfo userInfo;public String getInfo(){return userInfo.getName()+" address: "+userInfo.getAddress();}
}

2,使用starter
2.1,创建maven工程并配置pom.xml文件,加入自定义starter依赖

//省略
<dependencies><!--导入自定义starter--><dependency><groupId>cn.tianqing</groupId><artifactId>tianqing-spring-boot-starter</artifactId><version>1.0-SNAPSHOT</version></dependency>
</dependencies>

2.2,修改application.yml文件

xxx:name: xiaomingaddress: beijing

2.3,调用自定义starter中服务

@Component
public class CustomStarterTest {//注入自定义starter中的server类@AutowiredDMService dmService;@PostConstructpublic void task1() {System.out.println(dmService.getInfo());}
}

案例2:自定义拦截器记录服务执行时间

1.1,自定义starter的pom.xml文件中添加web依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><optional>true</optional>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId>
</dependency>

1.2,自定义MyLog注解

@Target(ElementType.METHOD)//仅在方法上使用
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {/*** 方法描述*/String desc() default "";
}

1.3,自定义日志拦截器MyLogInterceptor

/*** 日志拦截器*/
public class MyLogInterceptor extends HandlerInterceptorAdapter {private static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<>();public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {HandlerMethod handlerMethod = (HandlerMethod)handler;//获得被拦截的方法对象Method method = handlerMethod.getMethod();//获得方法上的注解MyLog myLog = method.getAnnotation(MyLog.class);if(myLog != null){//方法上加了MyLog注解,需要进行日志记录long startTime = System.currentTimeMillis();startTimeThreadLocal.set(startTime);}return true;}public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {HandlerMethod handlerMethod = (HandlerMethod)handler;//获得被拦截的方法对象Method method = handlerMethod.getMethod();//获得方法上的注解MyLog myLog = method.getAnnotation(MyLog.class);if(myLog != null){//方法上加了MyLog注解,需要进行日志记录long endTime = System.currentTimeMillis();//ThreadLocal中获取开始时间Long startTime = startTimeThreadLocal.get();long optTime = endTime - startTime;System.out.println("方法执行时间:" + optTime + "ms");String requestUri = request.getRequestURI();//类名+方法名String methodName = method.getDeclaringClass().getName() + "." + method.getName();String methodDesc = myLog.desc();System.out.println("请求uri:" + requestUri);System.out.println("请求方法名:" + methodName);System.out.println("方法描述:" + methodDesc);}}
}

1.4,创建自动配置类MyLogAutoConfiguration,用于自动配置拦截器、参数解析器等web组件

/*** 配置类,用于自动配置拦截器、参数解析器等web组件*/
@Configuration
public class MyLogAutoConfiguration implements WebMvcConfigurer{//注册自定义日志拦截器public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new MyLogInterceptor());}
}

1.5,在spring.factories中追加MyLogAutoConfiguration配置

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.meteorological.config.XXXAutoConfiguration,\
cn.meteorological.config.MyLogAutoConfiguration

2,使用自定义starter
2.1,Controller方法上加入@MyLog注解

@RestController
@RequestMapping("/hello")
public class HelloController {@Autowiredprivate HelloService helloService;//日志记录注解@MyLog(desc = "sayHello方法")@GetMapping("/say")public String sayHello(){return helloService.sayHello();}
}

2.2,访问地址:http://localhost:8080/hello/say,查看控制台输出:

请求uri:/hello/say
请求方法名:cn.meteorological.controller.HelloController.sayHello
方法描述:sayHello方法
方法执行时间:36ms

http://www.ppmy.cn/devtools/92486.html

相关文章

lodash判断是否是邮箱

在 JavaScript 中&#xff0c;可以使用 lodash 库中的 _.isString 函数来判断一个值是否为字符串&#xff0c;然后使用正则表达式来检查该字符串是否符合电子邮件的格式。以下是如何使用 lodash 来实现这一功能的示例代码&#xff1a; import _ from lodash;function isEmail(…

go之web框架gin

一、gin简介 Gin 是一个 go 写的 web 框架&#xff0c;具有高性能的优点。 二、快速使用 2.1 引入依赖 go get -u github.com/gin-gonic/gin 2.2 示例代码 type User struct {USERNAME string json:"username" }func main() {router : gin.Default()router.POST…

C语言——查漏补缺

前言 本篇博客主要记录一些C语言的遗漏点&#xff0c;完成查漏补缺的工作&#xff0c;如果读者感兴趣&#xff0c;可以看看下面的内容。都是一些小点&#xff0c;下面进入正文部分。 1. 字符汇聚 编写代码&#xff0c;演示多个字符从两端移动&#xff0c;向中间汇聚 #inclu…

sp eric靶机渗透测试

一、靶机下载地址 https://www.vulnhub.com/entry/sp-eric,274/ 二、信息收集 1、主机发现 # 使用命令 nmap 192.168.145.0/24 -sn | grep -B 2 "00:0C:29:FD:57:BE" 2、端口扫描 # 使用命令 nmap 192.168.145.211 -p- -sV 3、指纹识别 # 使用命令 whatweb 192…

vue前端根据接口返回的url 下载图片

downloadPicture(imgSrc, name) { const image new Image(); // 解决跨域 Canvas 污染问题 image.setAttribute("crossOrigin", "anonymous"); image.src imgSrc; image.onload () > { const canvas document.createElement("canvas"); c…

3D靓图!CEEMDAN-Kmeans-VMD-CNN-GRU-Attention双重分解卷积门控单元注意力多元时序预测

3D靓图&#xff01;CEEMDAN-Kmeans-VMD-CNN-GRU-Attention双重分解卷积门控单元注意力多元时序预测 目录 3D靓图&#xff01;CEEMDAN-Kmeans-VMD-CNN-GRU-Attention双重分解卷积门控单元注意力多元时序预测效果一览基本介绍程序设计参考资料 效果一览 基本介绍 1.Matlab实现CE…

基于S7-200 SMART实现PID控制仿真实验

关键字&#xff1a;Matalb&#xff1b;S7-200 SMART&#xff1b;Modbus TCP&#xff1b;PID控制 系列文章目录 基于S7-200 SMART实现一键启停 顺序功能图——&#xff08;二&#xff09;设计机组延时关机程序 基于S7-200 SMART实现Modbus TCP通信 基于S7-200 SMART实现MATLAB写…

10步搞定Python爬虫从零到精通!

学习Python网络爬虫可以分为以下几个步骤&#xff0c;每一步都包括必要的细节和示例代码&#xff0c;以帮助你从零开始掌握这一技能。 第一步&#xff1a;理解网络爬虫基础 什么是网络爬虫&#xff1f; 网络爬虫是一种自动化程序,用来从互联网上收集数据.它通过发送 HTTP 请求…