Compare commits

..
2 Commits
Author SHA1 Message Date
minglipro ed7f034ca0 v5.7.3
Gitea Actions Build / Build (push) Waiting to run
- exception: HttpStatusException、HttpStatusExceptionEnum 及 30 个 httpErrorXXX 快捷函数补齐 KDoc;快捷函数默认 message 改为对应状态短语

- exception: JsonFormatException 从 JsonParserException.kt 拆分为独立文件

- string: 新增 stringBuilder { ... } 工厂函数
2026-11-23 16:55:25 +08:00
minglipro 53e30351a7 v5.7.2
Gitea Actions Build / Build (push) Waiting to run
- spring: 新增 @FastServiceScan 扫描注解与 FastServiceScanRegistrar / FastServiceScannerProcessor,支持扫描 FastBaseIService 和 FastBaseIServiceNew3518 两个基类、value/basePackages 别名、缺失基类跳过

- spring: ApplicationDestroyedRunner / ApplicationReadyEventListener / ApplicationStartedRunner / ContextClosedEventListener 迁移为 Kotlin,弃用注解补全 @Deprecated + ReplaceWith

- build: 新增 VERSIONSTYPE 控制 RELEASES/SNAPSHOT 版本后缀,补充 Spring / MyBatis-Plus 测试依赖

- test: 新增 FastServiceScanRegistrarTest 5 个用例与 FastServiceScannerProcessorTest 2 个用例
2026-11-23 15:23:07 +08:00
22 changed files with 1395 additions and 385 deletions
+53
View File
@@ -4,6 +4,59 @@
本文件记录 mingli-utils 各版本的主要变更。 本文件记录 mingli-utils 各版本的主要变更。
## [5.7.3] - 2026-11-23
### 新增
- **string**:新增 `stringBuilder { ... }` 工厂函数,通过 `StringBuilder().apply { ... }`
创建并初始化 `StringBuilder`。
### 变更
- **exception**:`HttpStatusException`、`HttpStatusExceptionEnum` 及 30 个
`httpErrorXXX()` 快捷函数补齐 KDoc(状态码、参数、抛出异常);快捷函数的默认
`message` 从 `null` 改为对应状态短语(如 `"Bad Gateway"`、`"Not Found"`),
未显式传参时异常消息不再为空。
- **exception**:`JsonFormatException` 从 `JsonParserException.kt` 拆分为独立文件,
包名和公开 API 不变;`JsonParserException.kt` 只保留解析异常。
## [5.7.2] - 2026-11-23
### 新增
- **spring**:新增 `@FastServiceScan` 注解及 `FastServiceScanRegistrar`、
`FastServiceScannerProcessor`——扫描继承 `FastBaseIService` 或 `FastBaseIServiceNew3518`
的具体类并注册为 Spring Bean;仅在启动类/配置类标注该注解时生效,扫描时机在所有
`BeanDefinitionRegistryPostProcessor`(包括 `@MapperScan` 的 `MapperScannerConfigurer`)之后。
支持 `value` / `basePackages` / `basePackageClasses`,`value` 与 `basePackages` 通过
`@AliasFor` 互为别名;未指定包时使用标注类所在包;已标注 `@Component` / `@Service`
的类自动跳过,避免重复注册。
- **test**:新增 `FastServiceScanRegistrarTest`(5 个用例)与
`FastServiceScannerProcessorTest`(2 个用例,覆盖两个基类与某个基类缺失时的跳过逻辑)。
### 变更
- **spring**:`ApplicationDestroyedRunner`、`ApplicationReadyEventListener`、
`ApplicationStartedRunner`、`ContextClosedEventListener` 由 Java 迁移为 Kotlin 实现,
包名、属性及 `@AliasFor` 关系保持不变。
- **spring**:`ApplicationDestroyedRunner` / `ApplicationStartedRunner` 补全
`@Deprecated` + `ReplaceWith`,IDE 可一键替换为 `ContextClosedEventListener` /
`ApplicationReadyEventListener`;旧 Java 版本只有 `@Deprecated(since = ...)`。
- **build**:新增 `VERSIONSTYPE`(`r` = RELEASES,`s` = SNAPSHOT)控制版本后缀;
补充 Spring / MyBatis-Plus 测试依赖。
### 修复
- **spring**:`FastServiceScannerProcessor` 改为按类名探测两个服务基类,
仅引入一套 MyBatis-Plus 时只跳过缺失的基类,不再因类字面量加载父类失败抛出
`NoClassDefFoundError`。
### 注意
- 事件监听注解的 `defaultExecution` 属性仅在 Spring Framework 6.2+ 中提供;
在 Spring 5.3 下解析这些组合注解会抛出 `AnnotationConfigurationException`,使用方需按实际
Spring 版本选择。
## [5.7.0] - 2026-11-23 ## [5.7.0] - 2026-11-23
### 新增 ### 新增
+10 -3
View File
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils * ModuleName mingli-utils
* CurrentFile build.gradle.kts * CurrentFile build.gradle.kts
* LastUpdate 2026-11-23 10:24:07 * LastUpdate 2026-11-23 15:17:59
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -60,10 +60,12 @@ plugins {
kotlin("plugin.spring") version "2.1.0" kotlin("plugin.spring") version "2.1.0"
} }
val GROUPSID = providers.gradleProperty("GROUPSID").get() val GROUPSID = providers.gradleProperty("GROUPSID").get()
val VERSIONS = providers.gradleProperty("VERSIONS").get() val VERSION = providers.gradleProperty("VERSIONS").get()
val ARTIFACTID = providers.gradleProperty("ARTIFACTID").get() val ARTIFACTID = providers.gradleProperty("ARTIFACTID").get()
val JDKVERSIONS = providers.gradleProperty("JDKVERSIONS").get().toInt() val JDKVERSIONS = providers.gradleProperty("JDKVERSIONS").get().toInt()
val VERSIONSTYPE = providers.gradleProperty("VERSIONSTYPE").get()
val VERSIONS =
VERSION + if (VERSIONSTYPE == "s") "-SNAPSHOT" else if (VERSIONSTYPE == "r") "" else error("VERSIONSTYPE is not supported in gradle.properties $VERSIONSTYPE")
group = GROUPSID group = GROUPSID
version = VERSIONS version = VERSIONS
@@ -117,6 +119,11 @@ dependencies {
testImplementation("org.junit.jupiter:junit-jupiter:5.7.1") testImplementation("org.junit.jupiter:junit-jupiter:5.7.1")
testRuntimeOnly("org.junit.platform:junit-platform-launcher") testRuntimeOnly("org.junit.platform:junit-platform-launcher")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2") testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2")
testImplementation(fileTree("libs"))
testImplementation("com.baomidou:mybatis-plus-core:3.5.15")
testImplementation("com.baomidou:mybatis-plus-extension:3.5.15")
testImplementation("com.baomidou:mybatis-plus-spring:3.5.9")
testImplementation("org.springframework:spring-context:5.3.39")
testImplementation("org.redisson:redisson:4.8.0") testImplementation("org.redisson:redisson:4.8.0")
testImplementation("com.mingliqiye.logger:logger-log4j2:1.0.9") testImplementation("com.mingliqiye.logger:logger-log4j2:1.0.9")
testImplementation("com.google.code.gson:gson:2.13.2") testImplementation("com.google.code.gson:gson:2.13.2")
+5 -2
View File
@@ -16,10 +16,13 @@
# ProjectName mingli-utils # ProjectName mingli-utils
# ModuleName mingli-utils # ModuleName mingli-utils
# CurrentFile gradle.properties # CurrentFile gradle.properties
# LastUpdate 2026-11-23 10:43:58 # LastUpdate 2026-11-23 17:04:00
# UpdateUser MingLiPro # UpdateUser MingLiPro
# #
JDKVERSIONS=17 JDKVERSIONS=17
GROUPSID=com.mingliqiye.utils GROUPSID=com.mingliqiye.utils
ARTIFACTID=mingli-utils ARTIFACTID=mingli-utils
VERSIONS=5.7.0 # r = RELEASES
# s = SNAPSHOT
VERSIONSTYPE=r
VERSIONS=5.7.3
@@ -1,83 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ApplicationDestroyedRunner.java
* LastUpdate 2026-11-18 08:21:37
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AliasFor;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
/**
* 应用销毁(上下文关闭)事件监听注解。
*
* <p>标注在 Spring Bean 的方法上,当 Spring 应用上下文关闭
* ({@link ContextClosedEvent} 发布)时自动调用该方法。</p>
*
* @deprecated 已弃用,请改用 {@link ContextClosedEventListener}(监听相同事件,命名更规范)。
* @see ContextClosedEventListener
* @see EventListener
* @see ContextClosedEvent
*/
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@EventListener(ContextClosedEvent.class)
@Order
@Deprecated(since = "use ApplicationReadyEventListener")
public @interface ApplicationDestroyedRunner {
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* @return 条件表达式,默认为空字符串(无条件执行)
*/
@AliasFor(annotation = EventListener.class, attribute = "condition")
String condition() default "";
/**
* 当事件不是 {@link ContextClosedEvent} 类型时是否仍默认执行监听方法。
*
* @return 是否默认执行,默认为 true
*/
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
boolean defaultExecution() default true;
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* @return 监听器 id,默认为空字符串(自动生成)
*/
@AliasFor(annotation = EventListener.class, attribute = "id")
String id() default "";
/**
* 监听器的执行顺序,值越小优先级越高。
*
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
* @see Ordered#getOrder()
*/
@AliasFor(annotation = Order.class, attribute = "value")
int order() default Ordered.LOWEST_PRECEDENCE;
}
@@ -1,95 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ApplicationReadyEventListener.java
* LastUpdate 2026-11-18 08:21:57
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AliasFor;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
/**
* 应用就绪事件监听注解。
*
* <p>标注在 Spring Bean 的方法上,当 Spring Boot 应用完成启动并就绪
* ({@link ApplicationReadyEvent} 发布)时自动调用该方法,
* 等价于 {@code @EventListener(ApplicationReadyEvent.class)} 的组合简化写法。</p>
*
* <p>使用示例:</p>
* <pre>{@code
* @Component
* public class InitTask {
* @ApplicationReadyEventListener(order = 0)
* public void onReady() {
* // 应用就绪后执行的初始化逻辑
* }
* }
* }</pre>
*
* @see EventListener
* @see ApplicationReadyEvent
*/
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@EventListener(ApplicationReadyEvent.class)
@Order
public @interface ApplicationReadyEventListener {
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* @return 条件表达式,默认为空字符串(无条件执行)
*/
@AliasFor(annotation = EventListener.class, attribute = "condition")
String condition() default "";
/**
* 当事件不是 {@link ApplicationReadyEvent} 类型时是否仍默认执行监听方法。
*
* @return 是否默认执行,默认为 true
*/
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
boolean defaultExecution() default true;
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* @return 监听器 id,默认为空字符串(自动生成)
*/
@AliasFor(annotation = EventListener.class, attribute = "id")
String id() default "";
/**
* 监听器的执行顺序,值越小优先级越高。
*
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
* @see Ordered#getOrder()
*/
@AliasFor(annotation = Order.class, attribute = "value")
int order() default Ordered.LOWEST_PRECEDENCE;
}
@@ -1,84 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ApplicationStartedRunner.java
* LastUpdate 2026-11-18 08:21:57
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AliasFor;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
/**
* 应用启动完成事件监听注解。
*
* <p>标注在 Spring Bean 的方法上,当 Spring Boot 应用完成启动并就绪
* ({@link ApplicationReadyEvent} 发布)时自动调用该方法。</p>
*
* @deprecated 已弃用,请改用 {@link ApplicationReadyEventListener}(功能完全一致,命名更规范)。
* @see ApplicationReadyEventListener
* @see EventListener
* @see ApplicationReadyEvent
*/
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@EventListener(ApplicationReadyEvent.class)
@Order
@Deprecated(since = "use ApplicationReadyEventListener")
public @interface ApplicationStartedRunner {
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* @return 条件表达式,默认为空字符串(无条件执行)
*/
@AliasFor(annotation = EventListener.class, attribute = "condition")
String condition() default "";
/**
* 当事件不是 {@link ApplicationReadyEvent} 类型时是否仍默认执行监听方法。
*
* @return 是否默认执行,默认为 true
*/
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
boolean defaultExecution() default true;
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* @return 监听器 id,默认为空字符串(自动生成)
*/
@AliasFor(annotation = EventListener.class, attribute = "id")
String id() default "";
/**
* 监听器的执行顺序,值越小优先级越高。
*
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
* @see Ordered#getOrder()
*/
@AliasFor(annotation = Order.class, attribute = "value")
int order() default Ordered.LOWEST_PRECEDENCE;
}
@@ -1,93 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ContextClosedEventListener.java
* LastUpdate 2026-11-18 08:21:23
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AliasFor;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
/**
* 应用上下文关闭事件监听注解。
*
* <p>标注在 Spring Bean 的方法上,当 Spring 应用上下文关闭
* ({@link ContextClosedEvent} 发布)时自动调用该方法,
* 等价于 {@code @EventListener(ContextClosedEvent.class)} 的组合简化写法,
* 适用于应用停机前的资源清理、状态保存等场景。</p>
*
* <p>使用示例:</p>
* <pre>{@code
* @Component
* public class CleanupTask {
* @ContextClosedEventListener
* public void onClosed() {
* // 上下文关闭前执行的清理逻辑
* }
* }
* }</pre>
*
* @see EventListener
* @see ContextClosedEvent
*/
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@EventListener(ContextClosedEvent.class)
@Order
public @interface ContextClosedEventListener {
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* @return 条件表达式,默认为空字符串(无条件执行)
*/
@AliasFor(annotation = EventListener.class, attribute = "condition")
String condition() default "";
/**
* 当事件不是 {@link ContextClosedEvent} 类型时是否仍默认执行监听方法。
*
* @return 是否默认执行,默认为 true
*/
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
boolean defaultExecution() default true;
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* @return 监听器 id,默认为空字符串(自动生成)
*/
@AliasFor(annotation = EventListener.class, attribute = "id")
String id() default "";
/**
* 监听器的执行顺序,值越小优先级越高。
*
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
* @see Ordered#getOrder()
*/
@AliasFor(annotation = Order.class, attribute = "value")
int order() default Ordered.LOWEST_PRECEDENCE;
}
@@ -0,0 +1,94 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile FastServiceScan.java
* LastUpdate 2026-11-23 14:44:48
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation;
import com.mingliqiye.utils.springboot.autoconfigure.FastServiceScanRegistrar;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.AliasFor;
import java.lang.annotation.*;
/**
* 扫描继承自 {@code com.mingliqiye.utils.mybatisplus.FastBaseIService} 或
* {@code com.mingliqiye.utils.mybatisplus.FastBaseIServiceNew3518} 的具体类并注册为 Spring Bean。
* 两个基类分别对应旧版 {@code mybatis-plus-extension} 与新版 {@code mybatis-plus-spring},
* 子类都会被扫描到;行为与 {@code @MapperScan} 类似:只有标注了本注解的启动类/配置类才会触发扫描。
*
* <p>扫描由 {@link FastServiceScanRegistrar} 注册的
* {@code com.mingliqiye.utils.springboot.autoconfigure.FastServiceScannerProcessor} 完成,
* 后者是 {@code BeanFactoryPostProcessor},会在所有 {@code BeanDefinitionRegistryPostProcessor}
* (包括 {@code @MapperScan} 的 {@code MapperScannerConfigurer})之后执行,
* 因此扫描注册时机在 mapper 之后,服务里的 {@code baseMapper} 可以正常注入。</p>
*
* <p>已经标注 {@code @Component} / {@code @Service} 的类会被跳过,交给普通组件扫描处理,避免重复注册。</p>
*
* <p>Java 用法:</p>
* <pre>{@code
* @SpringBootApplication
* @MapperScan(basePackages = "com.example.mapper")
* @FastServiceScan(basePackages = "com.example.service")
* public class ExampleApplication {
* }
* }</pre>
*
* <p>Kotlin 用法:</p>
* <pre>{@code
* @SpringBootApplication
* @MapperScan(basePackages = ["com.example.mapper"])
* @FastServiceScan(basePackages = ["com.example.service"])
* class ExampleApplication
* }</pre>
*
* <p>不指定扫描包时,默认扫描标注类所在包。</p>
* <p>{@code Kotlin} 请指定 {@code Service} 为 {@code open}</p>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(FastServiceScanRegistrar.class)
public @interface FastServiceScan {
/**
* 要扫描的包,等价于 {@link #basePackages()}。
*
* @return 要扫描的包
*/
@AliasFor("basePackages")
String[] value() default {};
/**
* 要扫描的包。
*
* @return 要扫描的包
*/
@AliasFor("value")
String[] basePackages() default {};
/**
* 以这些类所在包作为扫描包。
*
* @return 用于推导扫描包的类
*/
Class<?>[] basePackageClasses() default {};
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile BadGatewayException.kt * CurrentFile BadGatewayException.kt
* LastUpdate 2026-10-22 22:07:34 * LastUpdate 2026-11-23 16:14:45
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -16,18 +16,28 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile HttpStatusException.kt * CurrentFile HttpStatusException.kt
* LastUpdate 2026-10-11 17:02:06 * LastUpdate 2026-11-23 17:02:00
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
import kotlin.reflect.KClass
/** /**
* 表示 HTTP 异常的基类,继承自 [RuntimeException]。 * HTTP 状态异常基类,供所有携带状态码的异常继承。
* *
* @param statusCode HTTP 状态码 * 子类在构造时固定 [statusCode];调用方可以据此统一生成 HTTP 响应,
* @param message 异常信息,默认为 null * 而不必为每一种状态码单独判断异常类型。
* @param cause 异常原因,默认为 null *
* 构造函数标注了 `@JvmOverloads`,Java 侧可以按不同参数个数调用。
*
* @property statusCode HTTP 状态码
* @param message 异常描述;为 `null` 时沿用父类行为
* @param throwable 导致该异常的原始异常
* @param enableSuppression 是否启用异常抑制
* @param writableStackTrace 是否生成堆栈信息
* @see MingLiUtilsBaseException
*/ */
open class HttpStatusException @JvmOverloads constructor( open class HttpStatusException @JvmOverloads constructor(
val statusCode: Int, val statusCode: Int,
@@ -36,3 +46,395 @@ open class HttpStatusException @JvmOverloads constructor(
enableSuppression: Boolean = false, enableSuppression: Boolean = false,
writableStackTrace: Boolean = true, writableStackTrace: Boolean = true,
) : MingLiUtilsBaseException(message, throwable, enableSuppression, writableStackTrace) ) : MingLiUtilsBaseException(message, throwable, enableSuppression, writableStackTrace)
/**
* HTTP 状态异常类型枚举。
*
* 每个枚举项绑定一个 [HttpStatusException] 子类:可以用 [kClazz] / [clazz] 按类型查找,
* 也可以用 [init] 按消息创建对应的异常实例。
*
* @property kClazz 异常类型的 Kotlin 类
* @property init 使用给定消息创建异常的工厂函数
*/
enum class HttpStatusExceptionEnum(
val kClazz: KClass<out HttpStatusException>,
val init: (message: String?) -> HttpStatusException,
) {
/** 502 Bad Gateway,对应 [BadGatewayException]。 */
BAD_GATEWAY_EXCEPTION(BadGatewayException::class, ::BadGatewayException),
/** 400 Bad Request,对应 [BadRequestException]。 */
BAD_REQUEST_EXCEPTION(BadRequestException::class, ::BadRequestException),
/** 409 Conflict,对应 [ConflictException]。 */
CONFLICT_EXCEPTION(ConflictException::class, ::ConflictException),
/** 403 Forbidden,对应 [ForbiddenException]。 */
FORBIDDEN_EXCEPTION(ForbiddenException::class, ::ForbiddenException),
/** 302 Found,对应 [FoundException]。 */
FOUND_EXCEPTION(FoundException::class, ::FoundException),
/** 504 Gateway Timeout,对应 [GatewayTimeoutException]。 */
GATEWAY_TIMEOUT_EXCEPTION(GatewayTimeoutException::class, ::GatewayTimeoutException),
/** 410 Gone,对应 [GoneException]。 */
GONE_EXCEPTION(GoneException::class, ::GoneException),
/** 505 HTTP Version Not Supported,对应 [HttpVersionNotSupportedException]。 */
HTTP_VERSION_NOT_SUPPORTED_EXCEPTION(HttpVersionNotSupportedException::class, ::HttpVersionNotSupportedException),
/** 500 Internal Server Error,对应 [InternalServerErrorException]。 */
INTERNAL_SERVER_ERROR_EXCEPTION(InternalServerErrorException::class, ::InternalServerErrorException),
/** 411 Length Required,对应 [LengthRequiredException]。 */
LENGTH_REQUIRED_EXCEPTION(LengthRequiredException::class, ::LengthRequiredException),
/** 405 Method Not Allowed,对应 [MethodNotAllowedException]。 */
METHOD_NOT_ALLOWED_EXCEPTION(MethodNotAllowedException::class, ::MethodNotAllowedException),
/** 301 Moved Permanently,对应 [MovedPermanentlyException]。 */
MOVED_PERMANENTLY_EXCEPTION(MovedPermanentlyException::class, ::MovedPermanentlyException),
/** 300 Multiple Choices,对应 [MultipleChoicesException]。 */
MULTIPLE_CHOICES_EXCEPTION(MultipleChoicesException::class, ::MultipleChoicesException),
/** 406 Not Acceptable,对应 [NotAcceptableException]。 */
NOT_ACCEPTABLE_EXCEPTION(NotAcceptableException::class, ::NotAcceptableException),
/** 404 Not Found,对应 [NotFoundException]。 */
NOT_FOUND_EXCEPTION(NotFoundException::class, ::NotFoundException),
/** 501 Not Implemented,对应 [NotImplementedException]。 */
NOT_IMPLEMENTED_EXCEPTION(NotImplementedException::class, ::NotImplementedException),
/** 304 Not Modified,对应 [NotModifiedException]。 */
NOT_MODIFIED_EXCEPTION(NotModifiedException::class, ::NotModifiedException),
/** 402 Payment Required,对应 [PaymentRequiredException]。 */
PAYMENT_REQUIRED_EXCEPTION(PaymentRequiredException::class, ::PaymentRequiredException),
/** 412 Precondition Failed,对应 [PreconditionFailedException]。 */
PRECONDITION_FAILED_EXCEPTION(PreconditionFailedException::class, ::PreconditionFailedException),
/** 407 Proxy Authentication Required,对应 [ProxyAuthenticationRequiredException]。 */
PROXY_AUTHENTICATION_REQUIRED_EXCEPTION(
ProxyAuthenticationRequiredException::class,
::ProxyAuthenticationRequiredException
),
/** 416 Requested Range Not Satisfiable,对应 [RequestedRangeNotSatisfiableException]。 */
REQUESTED_RANGE_NOT_SATISFIABLE_EXCEPTION(
RequestedRangeNotSatisfiableException::class,
::RequestedRangeNotSatisfiableException
),
/** 413 Request Entity Too Large,对应 [RequestEntityTooLargeException]。 */
REQUEST_ENTITY_TOO_LARGE_EXCEPTION(RequestEntityTooLargeException::class, ::RequestEntityTooLargeException),
/** 408 Request Timeout,对应 [RequestTimeoutException]。 */
REQUEST_TIMEOUT_EXCEPTION(RequestTimeoutException::class, ::RequestTimeoutException),
/** 414 Request URI Too Large,对应 [RequestUriTooLargeException]。 */
REQUEST_URI_TOO_LARGE_EXCEPTION(RequestUriTooLargeException::class, ::RequestUriTooLargeException),
/** 303 See Other,对应 [SeeOtherException]。 */
SEE_OTHER_EXCEPTION(SeeOtherException::class, ::SeeOtherException),
/** 503 Service Unavailable,对应 [ServiceUnavailableException]。 */
SERVICE_UNAVAILABLE_EXCEPTION(ServiceUnavailableException::class, ::ServiceUnavailableException),
/** 307 Temporary Redirect,对应 [TemporaryRedirectException]。 */
TEMPORARY_REDIRECT_EXCEPTION(TemporaryRedirectException::class, ::TemporaryRedirectException),
/** 401 Unauthorized,对应 [UnauthorizedException]。 */
UNAUTHORIZED_EXCEPTION(UnauthorizedException::class, ::UnauthorizedException),
/** 415 Unsupported Media Type,对应 [UnsupportedMediaTypeException]。 */
UNSUPPORTED_MEDIA_TYPE_EXCEPTION(UnsupportedMediaTypeException::class, ::UnsupportedMediaTypeException),
/** 305 Use Proxy,对应 [UseProxyException]。 */
USE_PROXY_EXCEPTION(UseProxyException::class, ::UseProxyException);
/** [kClazz] 对应的 Java 类,便于反射或按 `Class` 注册。 */
val clazz: Class<out HttpStatusException> = this.kClazz.java
}
/**
* 抛出 HTTP 502 Bad Gateway 异常。
*
* @param message 异常描述,默认为 `"Bad Gateway"`
* @throws BadGatewayException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError502(message: String? = "Bad Gateway"): Nothing = throw BadGatewayException(message)
/**
* 抛出 HTTP 400 Bad Request 异常。
*
* @param message 异常描述,默认为 `"Bad Request"`
* @throws BadRequestException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError400(message: String? = "Bad Request"): Nothing = throw BadRequestException(message)
/**
* 抛出 HTTP 409 Conflict 异常。
*
* @param message 异常描述,默认为 `"Conflict"`
* @throws ConflictException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError409(message: String? = "Conflict"): Nothing = throw ConflictException(message)
/**
* 抛出 HTTP 403 Forbidden 异常。
*
* @param message 异常描述,默认为 `"Forbidden"`
* @throws ForbiddenException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError403(message: String? = "Forbidden"): Nothing = throw ForbiddenException(message)
/**
* 抛出 HTTP 302 Found 异常。
*
* @param message 异常描述,默认为 `"Found"`
* @throws FoundException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError302(message: String? = "Found"): Nothing = throw FoundException(message)
/**
* 抛出 HTTP 504 Gateway Timeout 异常。
*
* @param message 异常描述,默认为 `"Gateway Timeout"`
* @throws GatewayTimeoutException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError504(message: String? = "Gateway Timeout"): Nothing = throw GatewayTimeoutException(message)
/**
* 抛出 HTTP 410 Gone 异常。
*
* @param message 异常描述,默认为 `"Gone"`
* @throws GoneException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError410(message: String? = "Gone"): Nothing = throw GoneException(message)
/**
* 抛出 HTTP 505 HTTP Version Not Supported 异常。
*
* @param message 异常描述,默认为 `"HTTP Version Not Supported"`
* @throws HttpVersionNotSupportedException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError505(message: String? = "HTTP Version Not Supported"): Nothing =
throw HttpVersionNotSupportedException(message)
/**
* 抛出 HTTP 500 Internal Server Error 异常。
*
* @param message 异常描述,默认为 `"Internal Server Error"`
* @throws InternalServerErrorException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError500(message: String? = "Internal Server Error"): Nothing =
throw InternalServerErrorException(message)
/**
* 抛出 HTTP 411 Length Required 异常。
*
* @param message 异常描述,默认为 `"Length Required"`
* @throws LengthRequiredException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError411(message: String? = "Length Required"): Nothing = throw LengthRequiredException(message)
/**
* 抛出 HTTP 405 Method Not Allowed 异常。
*
* @param message 异常描述,默认为 `"Method Not Allowed"`
* @throws MethodNotAllowedException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError405(message: String? = "Method Not Allowed"): Nothing = throw MethodNotAllowedException(message)
/**
* 抛出 HTTP 301 Moved Permanently 异常。
*
* @param message 异常描述,默认为 `"Moved Permanently"`
* @throws MovedPermanentlyException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError301(message: String? = "Moved Permanently"): Nothing = throw MovedPermanentlyException(message)
/**
* 抛出 HTTP 300 Multiple Choices 异常。
*
* @param message 异常描述,默认为 `"Multiple Choices"`
* @throws MultipleChoicesException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError300(message: String? = "Multiple Choices"): Nothing = throw MultipleChoicesException(message)
/**
* 抛出 HTTP 406 Not Acceptable 异常。
*
* @param message 异常描述,默认为 `"Not Acceptable"`
* @throws NotAcceptableException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError406(message: String? = "Not Acceptable"): Nothing = throw NotAcceptableException(message)
/**
* 抛出 HTTP 404 Not Found 异常。
*
* @param message 异常描述,默认为 `"Not Found"`
* @throws NotFoundException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError404(message: String? = "Not Found"): Nothing = throw NotFoundException(message)
/**
* 抛出 HTTP 501 Not Implemented 异常。
*
* @param message 异常描述,默认为 `"Not Implemented"`
* @throws NotImplementedException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError501(message: String? = "Not Implemented"): Nothing = throw NotImplementedException(message)
/**
* 抛出 HTTP 304 Not Modified 异常。
*
* @param message 异常描述,默认为 `"Not Modified"`
* @throws NotModifiedException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError304(message: String? = "Not Modified"): Nothing = throw NotModifiedException(message)
/**
* 抛出 HTTP 402 Payment Required 异常。
*
* @param message 异常描述,默认为 `"Payment Required"`
* @throws PaymentRequiredException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError402(message: String? = "Payment Required"): Nothing = throw PaymentRequiredException(message)
/**
* 抛出 HTTP 412 Precondition Failed 异常。
*
* @param message 异常描述,默认为 `"Precondition Failed"`
* @throws PreconditionFailedException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError412(message: String? = "Precondition Failed"): Nothing = throw PreconditionFailedException(message)
/**
* 抛出 HTTP 407 Proxy Authentication Required 异常。
*
* @param message 异常描述,默认为 `"Proxy Authentication Required"`
* @throws ProxyAuthenticationRequiredException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError407(message: String? = "Proxy Authentication Required"): Nothing =
throw ProxyAuthenticationRequiredException(message)
/**
* 抛出 HTTP 416 Requested Range Not Satisfiable 异常。
*
* @param message 异常描述,默认为 `"Requested Range Not Satisfiable"`
* @throws RequestedRangeNotSatisfiableException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError416(message: String? = "Requested Range Not Satisfiable"): Nothing =
throw RequestedRangeNotSatisfiableException(message)
/**
* 抛出 HTTP 413 Request Entity Too Large 异常。
*
* @param message 异常描述,默认为 `"Request Entity Too Large"`
* @throws RequestEntityTooLargeException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError413(message: String? = "Request Entity Too Large"): Nothing =
throw RequestEntityTooLargeException(message)
/**
* 抛出 HTTP 408 Request Timeout 异常。
*
* @param message 异常描述,默认为 `"Request Timeout"`
* @throws RequestTimeoutException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError408(message: String? = "Request Timeout"): Nothing = throw RequestTimeoutException(message)
/**
* 抛出 HTTP 414 Request URI Too Large 异常。
*
* @param message 异常描述,默认为 `"Request URI Too Large"`
* @throws RequestUriTooLargeException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError414(message: String? = "Request URI Too Large"): Nothing =
throw RequestUriTooLargeException(message)
/**
* 抛出 HTTP 303 See Other 异常。
*
* @param message 异常描述,默认为 `"See Other"`
* @throws SeeOtherException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError303(message: String? = "See Other"): Nothing = throw SeeOtherException(message)
/**
* 抛出 HTTP 503 Service Unavailable 异常。
*
* @param message 异常描述,默认为 `"Service Unavailable"`
* @throws ServiceUnavailableException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError503(message: String? = "Service Unavailable"): Nothing = throw ServiceUnavailableException(message)
/**
* 抛出 HTTP 307 Temporary Redirect 异常。
*
* @param message 异常描述,默认为 `"Temporary Redirect"`
* @throws TemporaryRedirectException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError307(message: String? = "Temporary Redirect"): Nothing = throw TemporaryRedirectException(message)
/**
* 抛出 HTTP 401 Unauthorized 异常。
*
* @param message 异常描述,默认为 `"Unauthorized"`
* @throws UnauthorizedException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError401(message: String? = "Unauthorized"): Nothing = throw UnauthorizedException(message)
/**
* 抛出 HTTP 415 Unsupported Media Type 异常。
*
* @param message 异常描述,默认为 `"Unsupported Media Type"`
* @throws UnsupportedMediaTypeException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError415(message: String? = "Unsupported Media Type"): Nothing =
throw UnsupportedMediaTypeException(message)
/**
* 抛出 HTTP 305 Use Proxy 异常。
*
* @param message 异常描述,默认为 `"Use Proxy"`
* @throws UseProxyException 总是抛出
*/
@Suppress("NOTHING_TO_INLINE")
inline fun httpError305(message: String? = "Use Proxy"): Nothing = throw UseProxyException(message)
@@ -0,0 +1,38 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JsonFormatException.kt
* LastUpdate 2026-11-23 16:14:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.exception
/**
* 表示 JSON 格式不正确时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class JsonFormatException @JvmOverloads constructor(
message: String? = null,
throwable: Throwable? = null,
enableSuppression: Boolean = false,
writableStackTrace: Boolean = true,
) : JsonException(message, throwable, enableSuppression, writableStackTrace)
@@ -16,12 +16,13 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile JsonParserException.kt * CurrentFile JsonParserException.kt
* LastUpdate 2026-11-17 16:22:52 * LastUpdate 2026-11-23 16:14:00
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.exception package com.mingliqiye.utils.exception
/** /**
* 表示 JSON 解析过程中发生的异常。 * 表示 JSON 解析过程中发生的异常。
* *
@@ -36,19 +37,3 @@ class JsonParserException @JvmOverloads constructor(
enableSuppression: Boolean = false, enableSuppression: Boolean = false,
writableStackTrace: Boolean = true, writableStackTrace: Boolean = true,
) : JsonException(message, throwable, enableSuppression, writableStackTrace) ) : JsonException(message, throwable, enableSuppression, writableStackTrace)
/**
* 表示 JSON 格式不正确时抛出的异常。
*
* @param message 异常信息,默认为 null
* @param throwable 异常原因,默认为 null
* @param enableSuppression 是否启用异常抑制,默认为 false
* @param writableStackTrace 是否可写入堆栈跟踪信息,默认为 true
*/
class JsonFormatException @JvmOverloads constructor(
message: String? = null,
throwable: Throwable? = null,
enableSuppression: Boolean = false,
writableStackTrace: Boolean = true,
) : JsonException(message, throwable, enableSuppression, writableStackTrace)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile NotFoundResourceException.kt * CurrentFile NotFoundResourceException.kt
* LastUpdate 2026-10-11 16:53:58 * LastUpdate 2026-11-23 16:38:55
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -0,0 +1,87 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ApplicationDestroyedRunner.kt
* LastUpdate 2026-11-23 15:07:06
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation
import org.springframework.context.event.ContextClosedEvent
import org.springframework.context.event.EventListener
import org.springframework.core.Ordered
import org.springframework.core.annotation.AliasFor
import org.springframework.core.annotation.Order
/**
* 应用销毁(上下文关闭)事件监听注解。
*
* 标注在 Spring Bean 的方法上,当 Spring 应用上下文关闭
* ([ContextClosedEvent] 发布)时自动调用该方法。
*
* 已弃用,请改用 [ContextClosedEventListener](监听相同事件,命名更规范)。
*
* @see ContextClosedEventListener
* @see EventListener
* @see ContextClosedEvent
*/
@Deprecated(
message = "已弃用,请改用 ContextClosedEventListener(监听相同事件,命名更规范)",
replaceWith = ReplaceWith(
expression = "ContextClosedEventListener",
imports = ["com.mingliqiye.utils.springboot.annotation.ContextClosedEventListener"],
),
)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@EventListener(ContextClosedEvent::class)
@Order
annotation class ApplicationDestroyedRunner(
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* 默认为空字符串,表示无条件执行。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "condition")
val condition: String = "",
/**
* 当事件不是 [ContextClosedEvent] 类型时是否仍默认执行监听方法。
*
* 默认为 `true`。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "defaultExecution")
val defaultExecution: Boolean = true,
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* 默认为空字符串,表示自动生成。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "id")
val id: String = "",
/**
* 监听器的执行顺序,值越小优先级越高。
*
* 默认为 [Ordered.LOWEST_PRECEDENCE]。
*/
@get:AliasFor(annotation = Order::class, attribute = "value")
val order: Int = Ordered.LOWEST_PRECEDENCE,
)
@@ -0,0 +1,88 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ApplicationReadyEventListener.kt
* LastUpdate 2026-11-23 15:07:06
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.context.event.EventListener
import org.springframework.core.Ordered
import org.springframework.core.annotation.AliasFor
import org.springframework.core.annotation.Order
/**
* 应用就绪事件监听注解。
*
* 标注在 Spring Bean 的方法上,当 Spring Boot 应用完成启动并就绪
* ([ApplicationReadyEvent] 发布)时自动调用该方法,
* 等价于 `@EventListener(ApplicationReadyEvent::class)` 的组合简化写法。
*
* ```kotlin
* @Component
* class InitTask {
* @ApplicationReadyEventListener(order = 0)
* fun onReady() {
* // 应用就绪后执行的初始化逻辑
* }
* }
* ```
*
* @see EventListener
* @see ApplicationReadyEvent
*/
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@EventListener(ApplicationReadyEvent::class)
@Order
annotation class ApplicationReadyEventListener(
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* 默认为空字符串,表示无条件执行。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "condition")
val condition: String = "",
/**
* 当事件不是 [ApplicationReadyEvent] 类型时是否仍默认执行监听方法。
*
* 默认为 `true`。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "defaultExecution")
val defaultExecution: Boolean = true,
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* 默认为空字符串,表示自动生成。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "id")
val id: String = "",
/**
* 监听器的执行顺序,值越小优先级越高。
*
* 默认为 [Ordered.LOWEST_PRECEDENCE]。
*/
@get:AliasFor(annotation = Order::class, attribute = "value")
val order: Int = Ordered.LOWEST_PRECEDENCE,
)
@@ -0,0 +1,87 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ApplicationStartedRunner.kt
* LastUpdate 2026-11-23 15:07:06
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.context.event.EventListener
import org.springframework.core.Ordered
import org.springframework.core.annotation.AliasFor
import org.springframework.core.annotation.Order
/**
* 应用启动完成事件监听注解。
*
* 标注在 Spring Bean 的方法上,当 Spring Boot 应用完成启动并就绪
* ([ApplicationReadyEvent] 发布)时自动调用该方法。
*
* 已弃用,请改用 [ApplicationReadyEventListener](功能完全一致,命名更规范)。
*
* @see ApplicationReadyEventListener
* @see EventListener
* @see ApplicationReadyEvent
*/
@Deprecated(
message = "已弃用,请改用 ApplicationReadyEventListener(功能完全一致,命名更规范)",
replaceWith = ReplaceWith(
expression = "ApplicationReadyEventListener",
imports = ["com.mingliqiye.utils.springboot.annotation.ApplicationReadyEventListener"],
),
)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@EventListener(ApplicationReadyEvent::class)
@Order
annotation class ApplicationStartedRunner(
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* 默认为空字符串,表示无条件执行。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "condition")
val condition: String = "",
/**
* 当事件不是 [ApplicationReadyEvent] 类型时是否仍默认执行监听方法。
*
* 默认为 `true`。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "defaultExecution")
val defaultExecution: Boolean = true,
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* 默认为空字符串,表示自动生成。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "id")
val id: String = "",
/**
* 监听器的执行顺序,值越小优先级越高。
*
* 默认为 [Ordered.LOWEST_PRECEDENCE]。
*/
@get:AliasFor(annotation = Order::class, attribute = "value")
val order: Int = Ordered.LOWEST_PRECEDENCE,
)
@@ -0,0 +1,89 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ContextClosedEventListener.kt
* LastUpdate 2026-11-23 15:07:06
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation
import org.springframework.context.event.ContextClosedEvent
import org.springframework.context.event.EventListener
import org.springframework.core.Ordered
import org.springframework.core.annotation.AliasFor
import org.springframework.core.annotation.Order
/**
* 应用上下文关闭事件监听注解。
*
* 标注在 Spring Bean 的方法上,当 Spring 应用上下文关闭
* ([ContextClosedEvent] 发布)时自动调用该方法,
* 等价于 `@EventListener(ContextClosedEvent::class)` 的组合简化写法,
* 适用于应用停机前的资源清理、状态保存等场景。
*
* ```kotlin
* @Component
* class CleanupTask {
* @ContextClosedEventListener
* fun onClosed() {
* // 上下文关闭前执行的清理逻辑
* }
* }
* ```
*
* @see EventListener
* @see ContextClosedEvent
*/
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.ANNOTATION_CLASS)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@EventListener(ContextClosedEvent::class)
@Order
annotation class ContextClosedEventListener(
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* 默认为空字符串,表示无条件执行。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "condition")
val condition: String = "",
/**
* 当事件不是 [ContextClosedEvent] 类型时是否仍默认执行监听方法。
*
* 默认为 `true`。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "defaultExecution")
val defaultExecution: Boolean = true,
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* 默认为空字符串,表示自动生成。
*/
@get:AliasFor(annotation = EventListener::class, attribute = "id")
val id: String = "",
/**
* 监听器的执行顺序,值越小优先级越高。
*
* 默认为 [Ordered.LOWEST_PRECEDENCE]。
*/
@get:AliasFor(annotation = Order::class, attribute = "value")
val order: Int = Ordered.LOWEST_PRECEDENCE,
)
@@ -0,0 +1,94 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile FastServiceScanRegistrar.kt
* LastUpdate 2026-11-23 14:21:18
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure
import com.mingliqiye.utils.springboot.annotation.FastServiceScan
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.beans.factory.support.BeanDefinitionRegistry
import org.springframework.beans.factory.support.RootBeanDefinition
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar
import org.springframework.core.type.AnnotationMetadata
import org.springframework.util.ClassUtils
/**
* [FastServiceScan] 的注册器:解析注解上的扫描包,并把 [FastServiceScannerProcessor] 注册成 Bean。
*
* 通过 Spring 的 `MergedAnnotation.synthesize()` 读取注解,这样 `value` 与 `basePackages`
* 之间的 `@AliasFor` 会像 `@MapperScan` 一样被正确合并(两者同时指定不同值时也会按 Spring
* 的规则报错,而不是被静默合并)。
*
* 这里不直接扫描,而是注册一个 `BeanFactoryPostProcessor`,由 Spring 在所有
* `BeanDefinitionRegistryPostProcessor`(如 `@MapperScan` 的 `MapperScannerConfigurer`)之后执行,
* 从而保证扫描注册时机在 mapper 之后。
*/
class FastServiceScanRegistrar : ImportBeanDefinitionRegistrar {
override fun registerBeanDefinitions(
importingClassMetadata: AnnotationMetadata,
registry: BeanDefinitionRegistry,
) {
val mergedAnnotation = importingClassMetadata.annotations.get(FastServiceScan::class.java)
if (!mergedAnnotation.isPresent) return
// synthesize 会应用 @AliasFor,value/basePackages 指向同一个值
val annotation = mergedAnnotation.synthesize()
val packages = resolvePackages(annotation, importingClassMetadata)
if (packages.isEmpty()) return
if (registry.containsBeanDefinition(PROCESSOR_BEAN_NAME)) return
val definition = RootBeanDefinition(FastServiceScannerProcessor::class.java)
definition.constructorArgumentValues.addIndexedArgumentValue(0, packages.toTypedArray())
definition.role = BeanDefinition.ROLE_INFRASTRUCTURE
registry.registerBeanDefinition(PROCESSOR_BEAN_NAME, definition)
}
/**
* 解析注解上的扫描包;未指定时取标注类所在包。
*/
private fun resolvePackages(
annotation: FastServiceScan,
importingClassMetadata: AnnotationMetadata,
): Set<String> {
val packages = LinkedHashSet<String>()
// value 与 basePackages 互为 @AliasFor,这里各读一遍只是防御;重复值会被 Set 去重
for (packageName in annotation.value) {
if (packageName.isNotBlank()) packages += packageName.trim()
}
for (packageName in annotation.basePackages) {
if (packageName.isNotBlank()) packages += packageName.trim()
}
for (baseClass in annotation.basePackageClasses) {
packages += ClassUtils.getPackageName(baseClass.java)
}
if (packages.isEmpty()) {
packages += ClassUtils.getPackageName(importingClassMetadata.className)
}
return packages
}
companion object {
private const val PROCESSOR_BEAN_NAME = "fastServiceScannerProcessor"
}
}
@@ -0,0 +1,137 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile FastServiceScannerProcessor.kt
* LastUpdate 2026-11-23 14:05:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import org.springframework.beans.factory.config.BeanFactoryPostProcessor
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory
import org.springframework.beans.factory.support.BeanDefinitionRegistry
import org.springframework.context.annotation.AnnotationBeanNameGenerator
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider
import org.springframework.core.Ordered
import org.springframework.core.type.filter.AnnotationTypeFilter
import org.springframework.core.type.filter.AssignableTypeFilter
import org.springframework.stereotype.Component
import org.springframework.util.ClassUtils
/**
* 扫描继承自 `com.mingliqiye.utils.mybatisplus.FastBaseIService` 或
* `com.mingliqiye.utils.mybatisplus.FastBaseIServiceNew3518` 的具体类并注册为 Spring Bean。
*
* 两个基类分别适配旧版 `mybatis-plus-extension` 与新版 `mybatis-plus-spring`,哪个子类都能扫到。
* 基类按类名在运行期探测:缺少对应 MyBatis-Plus 依赖时只跳过该基类,
* 不会因为类字面量加载父类失败而抛 `NoClassDefFoundError` 导致启动中断。
*
* 这是一个 [BeanFactoryPostProcessor],Spring 保证它在所有
* `BeanDefinitionRegistryPostProcessor`(包括 `@MapperScan` 的 `MapperScannerConfigurer`)之后执行,
* 因此 mapper 的 BeanDefinition 已经注册完毕,服务里的 `baseMapper` 注入不会因为时机问题失败。
*
* 已经标注 `@Component` / `@Service` 的类会交给普通组件扫描,这里跳过以避免重复注册。
*
* @param basePackages 要扫描的包
*/
class FastServiceScannerProcessor(
private val basePackages: Array<String>,
) : BeanFactoryPostProcessor, Ordered {
private val log = MingLiLoggerFactory.getLogger<FastServiceScannerProcessor>()
override fun postProcessBeanFactory(beanFactory: ConfigurableListableBeanFactory) {
val registry = beanFactory as? BeanDefinitionRegistry ?: return
if (basePackages.isEmpty()) return
val classLoader = beanFactory.beanClassLoader ?: FastServiceScannerProcessor::class.java.classLoader
val scanner = ClassPathScanningCandidateComponentProvider(false).apply {
// 已有 @Component/@Service 的由组件扫描负责,避免重复注册
addExcludeFilter(AnnotationTypeFilter(Component::class.java))
}
var includeFilterCount = 0
for (baseClassName in BASE_SERVICE_CLASS_NAMES) {
// isPresent 内部 catch Throwable,父类缺失导致的 NoClassDefFoundError 也会返回 false
if (!ClassUtils.isPresent(baseClassName, classLoader)) {
log.debug("跳过未加载的服务基类: {}", baseClassName)
continue
}
val baseClass = try {
ClassUtils.forName(baseClassName, classLoader)
} catch (t: Throwable) {
log.debug("加载服务基类失败,已跳过: {}", baseClassName, t)
continue
}
// 多个 include filter 之间是 OR 关系
scanner.addIncludeFilter(AssignableTypeFilter(baseClass))
includeFilterCount++
}
if (includeFilterCount == 0) {
log.debug("没有可用的服务基类,跳过 FastBaseIService 扫描: packages={}", basePackages.toList())
return
}
val nameGenerator = AnnotationBeanNameGenerator()
var registered = 0
for (basePackage in basePackages) {
for (candidate in scanner.findCandidateComponents(basePackage)) {
val className = candidate.beanClassName ?: continue
val beanName = nameGenerator.generateBeanName(candidate, registry)
val existing = if (registry.containsBeanDefinition(beanName)) {
registry.getBeanDefinition(beanName)
} else null
when {
existing == null -> {
registry.registerBeanDefinition(beanName, candidate)
registered++
}
existing.beanClassName == className -> Unit
else -> {
// 不同包下简单类名相同,用全限定名避免覆盖
registry.registerBeanDefinition(className, candidate)
registered++
}
}
}
}
log.debug(
"FastBaseIService/FastBaseIServiceNew3518 扫描完成: packages={}, registered={}",
basePackages.toList(),
registered,
)
}
override fun getOrder(): Int = Ordered.LOWEST_PRECEDENCE
companion object {
/**
* 服务基类全限定名。用字符串而不是类字面量,避免运行期缺少对应 MyBatis-Plus 依赖时加载失败。
*/
private val BASE_SERVICE_CLASS_NAMES = listOf(
"com.mingliqiye.utils.mybatisplus.FastBaseIService",
"com.mingliqiye.utils.mybatisplus.FastBaseIServiceNew3518",
)
}
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile StringUtils.kt * CurrentFile StringUtils.kt
* LastUpdate 2026-03-12 10:05:22 * LastUpdate 2026-11-23 16:31:17
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@file:JvmName("StringUtils") @file:JvmName("StringUtils")
@@ -202,6 +202,16 @@ fun String.stringBuilder(): java.lang.StringBuilder {
return StringBuilder(this) return StringBuilder(this)
} }
/**
* 根据当前字符串创建一个StringBuilder实例
*
* @return 包含当前字符串内容的StringBuilder实例
*/
fun stringBuilder(caller: StringBuilder.() -> Unit): StringBuilder {
return StringBuilder().apply(caller)
}
/** /**
* 将字符串按照指定分隔符进行分割 * 将字符串按照指定分隔符进行分割
* @param str 需要分割的字符串 * @param str 需要分割的字符串
@@ -0,0 +1,115 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.test
* CurrentFile FastServiceScanRegistrarTest.kt
* LastUpdate 2026-11-23 14:21:18
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure
import com.mingliqiye.utils.springboot.annotation.FastServiceScan
import org.junit.jupiter.api.Assertions.assertArrayEquals
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.support.DefaultListableBeanFactory
import org.springframework.core.type.AnnotationMetadata
/**
* FastServiceScanRegistrar 的单元测试,不启动 Spring 容器,只验证注解解析与注册行为。
*/
class FastServiceScanRegistrarTest {
@FastServiceScan(basePackages = ["com.example.service"])
private class ExplicitPackagesConfig
@FastServiceScan("com.example.value")
private class ValueAliasConfig
@FastServiceScan(basePackageClasses = [FastServiceScanRegistrarTest::class])
private class ClassPackagesConfig
@FastServiceScan
private class DefaultPackageConfig
/** 测试显式 basePackages 会注册扫描器并使用配置的包 */
@Test
fun testExplicitPackages() {
val registry = DefaultListableBeanFactory()
val metadata = AnnotationMetadata.introspect(ExplicitPackagesConfig::class.java)
FastServiceScanRegistrar().registerBeanDefinitions(metadata, registry)
assertTrue(registry.containsBeanDefinition("fastServiceScannerProcessor"))
val beanDefinition = registry.getBeanDefinition("fastServiceScannerProcessor")
val packages = beanDefinition.constructorArgumentValues.getIndexedArgumentValue(0, Array<String>::class.java)?.value
assertArrayEquals(arrayOf("com.example.service"), packages as Array<*>)
}
/** 测试 value 与 basePackages 的 @AliasFor 生效 */
@Test
fun testValueAlias() {
val registry = DefaultListableBeanFactory()
val metadata = AnnotationMetadata.introspect(ValueAliasConfig::class.java)
FastServiceScanRegistrar().registerBeanDefinitions(metadata, registry)
val beanDefinition = registry.getBeanDefinition("fastServiceScannerProcessor")
val packages = beanDefinition.constructorArgumentValues.getIndexedArgumentValue(0, Array<String>::class.java)?.value
assertArrayEquals(arrayOf("com.example.value"), packages as Array<*>)
}
/** 测试 basePackageClasses 会转换为其所在包 */
@Test
fun testBasePackageClasses() {
val registry = DefaultListableBeanFactory()
val metadata = AnnotationMetadata.introspect(ClassPackagesConfig::class.java)
FastServiceScanRegistrar().registerBeanDefinitions(metadata, registry)
val beanDefinition = registry.getBeanDefinition("fastServiceScannerProcessor")
val packages = beanDefinition.constructorArgumentValues.getIndexedArgumentValue(0, Array<String>::class.java)?.value
assertArrayEquals(arrayOf("com.mingliqiye.utils.springboot.autoconfigure"), packages as Array<*>)
}
/** 测试不写包名时默认使用标注类所在包 */
@Test
fun testDefaultPackage() {
val registry = DefaultListableBeanFactory()
val metadata = AnnotationMetadata.introspect(DefaultPackageConfig::class.java)
FastServiceScanRegistrar().registerBeanDefinitions(metadata, registry)
val beanDefinition = registry.getBeanDefinition("fastServiceScannerProcessor")
val packages = beanDefinition.constructorArgumentValues.getIndexedArgumentValue(0, Array<String>::class.java)?.value
assertArrayEquals(arrayOf("com.mingliqiye.utils.springboot.autoconfigure"), packages as Array<*>)
}
/** 测试重复处理同一个配置类不会重复注册扫描器 */
@Test
fun testIdempotentRegistration() {
val registry = DefaultListableBeanFactory()
val metadata = AnnotationMetadata.introspect(ExplicitPackagesConfig::class.java)
val registrar = FastServiceScanRegistrar()
registrar.registerBeanDefinitions(metadata, registry)
registrar.registerBeanDefinitions(metadata, registry)
assertEquals(1, registry.beanDefinitionCount)
}
}
@@ -0,0 +1,76 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.test
* CurrentFile FastServiceScannerProcessorTest.kt
* LastUpdate 2026-11-23 14:05:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure
import com.mingliqiye.utils.mybatisplus.FastBaseIService
import com.mingliqiye.utils.mybatisplus.FastBaseIServiceNew3518
import com.mingliqiye.utils.mybatisplus.FastBaseMapper
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.support.DefaultListableBeanFactory
private class ScanTestEntity
private interface ScanTestMapper : FastBaseMapper<ScanTestEntity>
private class LegacyScanTestService : FastBaseIService<ScanTestEntity, ScanTestMapper>()
private class NewScanTestService : FastBaseIServiceNew3518<ScanTestEntity, ScanTestMapper>()
/**
* FastServiceScannerProcessor 的扫描测试:两个基类的子类都应被注册。
*/
class FastServiceScannerProcessorTest {
@Test
fun testScansBothBaseServices() {
val registry = DefaultListableBeanFactory()
FastServiceScannerProcessor(arrayOf("com.mingliqiye.utils.springboot.autoconfigure"))
.postProcessBeanFactory(registry)
assertTrue(registry.containsBeanDefinition("legacyScanTestService"))
assertTrue(registry.containsBeanDefinition("newScanTestService"))
}
/** 测试某个基类加载失败时只跳过该基类,不抛 NoClassDefFoundError */
@Test
fun testMissingBaseClassIsSkipped() {
val registry = DefaultListableBeanFactory()
registry.beanClassLoader = object : ClassLoader(FastServiceScannerProcessorTest::class.java.classLoader) {
override fun loadClass(name: String, resolve: Boolean): Class<*> {
if (name == "com.mingliqiye.utils.mybatisplus.FastBaseIService") {
throw ClassNotFoundException(name)
}
return super.loadClass(name, resolve)
}
}
FastServiceScannerProcessor(arrayOf("com.mingliqiye.utils.springboot.autoconfigure"))
.postProcessBeanFactory(registry)
assertTrue(registry.containsBeanDefinition("newScanTestService"))
assertFalse(registry.containsBeanDefinition("legacyScanTestService"))
}
}