This commit is contained in:
2026-10-26 23:22:29 +08:00
parent 85fd391849
commit 0e5ce5597b
19 changed files with 852 additions and 1579 deletions
@@ -13,10 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ProjectName FastBaseMapper.kt
* ModuleName mingli-utils.main
* CurrentFile Jackson3AutoConfiguration.kt
* LastUpdate 2026-10-02 16:11:12
* LastUpdate 2026-10-26 23:22:18
* UpdateUser MingLiPro
*/
@@ -38,15 +38,35 @@ open class Jackson3AutoConfiguration {
private val logger = MingLiLoggerFactory.getLogger<Jackson3AutoConfiguration>()
@Bean
@ConditionalOnMissingBean(JsonMapperBuilderCustomizer::class)
open fun myJsonMapperCustomizer(): JsonMapperBuilderCustomizer {
/**
* 注册 UUID 的 Jackson 3 序列化/反序列化模块。
*
* 如需替换 UUID 处理逻辑,注册名为 [UUIDJsonConverterJsonMapperCustomizer]
* 的 [JsonMapperBuilderCustomizer] Bean 即可,本 Bean 将自动跳过。
*/
@Bean("UUIDJsonConverterJsonMapperCustomizer")
@ConditionalOnMissingBean(name = ["UUIDJsonConverterJsonMapperCustomizer"])
open fun getUUIDJsonConverterJsonMapperCustomizer(): JsonMapperBuilderCustomizer {
return JsonMapperBuilderCustomizer { builder ->
builder
.addModule(UUIDJsonConverter.getJsonConverter().getJackson3Module())
.addModule(DateTimeJsonConverter.getJsonConverter().getJackson3Module())
builder.addModule(UUIDJsonConverter.getJsonConverter().getJackson3Module())
}.also {
logger.info("MingliUtils Jackson3 Serializers created")
logger.info("MingliUtils Jackson3 UUID Serializers created")
}
}
/**
* 注册日期时间的 Jackson 3 序列化/反序列化模块。
*
* 如需替换日期时间处理逻辑,注册名为 [DateTimeJsonConverterJsonMapperCustomizer]
* 的 [JsonMapperBuilderCustomizer] Bean 即可,本 Bean 将自动跳过。
*/
@Bean("DateTimeJsonConverterJsonMapperCustomizer")
@ConditionalOnMissingBean(name = ["DateTimeJsonConverterJsonMapperCustomizer"])
open fun getDateTimeJsonConverterJsonMapperCustomizer(): JsonMapperBuilderCustomizer {
return JsonMapperBuilderCustomizer { builder ->
builder.addModule(DateTimeJsonConverter.getJsonConverter().getJackson3Module())
}.also {
logger.info("MingliUtils Jackson3 DateTime Serializers created")
}
}
}
@@ -13,10 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ProjectName FastBaseMapper.kt
* ModuleName mingli-utils.main
* CurrentFile Jackson3JsonApiAutoConfiguration.kt
* LastUpdate 2026-10-02 16:11:02
* LastUpdate 2026-10-26 23:22:18
* UpdateUser MingLiPro
*/
@@ -33,26 +33,75 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.context.annotation.Bean
import tools.jackson.databind.json.JsonMapper
/**
* 基于 Jackson 3 的 [JsonApi] 自动配置。
*
* 在类路径存在 Jackson 3(`tools.jackson.databind.json.JsonMapper`)
* 及 Spring Boot 的 Jackson 自动配置时生效,将容器中的 [JsonMapper]
* 包装为 [Jackson3JsonApi] 并以 [JsonApi] 类型注册为 Bean,
* 同时尝试初始化全局单例 [JSONA]。
*
* ## 生效顺序
*
* 本类依赖 [Jackson3AutoConfiguration] 注册的 `JsonMapper` 构建定制器,
* 通过 `@AutoConfigureAfter` 保证在其之后处理,确保 `JsonMapper` 已按
* 自定义模块完成配置。
*
* ## 覆盖方式
*
* 若调用方需要自定义 [JsonApi] 实现,只需自行声明一个 [JsonApi] Bean,
* 本配置的 `@ConditionalOnMissingBean(JsonApi::class)` 将自动跳过创建。
*
* ## 全局单例
*
* [JSONA] 是进程级全局 JSON 访问入口。本配置在创建 Bean 后尝试读取
* [JSONA] 当前实例;若尚未设置(读取抛 [NullPointerException]),
* 则将本次创建的 [JsonApi] 设置为其全局实现。若调用方已在更早阶段
* 设置过 [JSONA],则保留既有实现,不覆盖。
*
* @see Jackson3AutoConfiguration
* @see Jackson3JsonApi
*/
@ConditionalOnClass(name = ["tools.jackson.databind.json.JsonMapper", "org.springframework.boot.jackson.autoconfigure.JacksonAutoConfiguration"])
@AutoConfigureAfter(name = ["com.mingliqiye.utils.springboot.autoconfigure.Jackson3AutoConfiguration"])
open class Jackson3JsonApiAutoConfiguration {
private val logger = MingLiLoggerFactory.getLogger<Jackson3JsonApiAutoConfiguration>()
companion object {
private val logger = MingLiLoggerFactory.getLogger<Jackson3JsonApiAutoConfiguration>()
}
/**
* 创建并注册默认的 [JsonApi] Bean。
*
* 使用容器中的 [JsonMapper] 构造 [Jackson3JsonApi]。读取器直接返回该 [JsonMapper];
* 写入器被设计为抛出 [JsonException],即本实现不允许通过 [JsonApi] 替换底层
* `JsonMapper`,底层实例由 Spring 容器统一管理。
*
* 创建完成后会尝试初始化全局 [JSONA]:
* - 若 [JSONA] 尚未设置,则设置为本实例;
* - 若已设置,则保留既有实现。
*
* 该 Bean 仅在容器中不存在其他 [JsonApi] 时创建。
*
* @param jsonMapper 容器中的 Jackson 3 映射器
* @return 基于 Jackson 3 的 JSON 访问门面
*/
@Bean
@ConditionalOnMissingBean(JsonApi::class)
open fun jsonApi(jsonMapper: JsonMapper): JsonApi {
return Jackson3JsonApi(
get = { jsonMapper },
set = { throw JsonException("JSON API set method is not allowed.") }).also {
logger.info("JsonApi Bean Auto Configuration Success")
try {
JSONA.getJsonApi()
} catch (_: NullPointerException) {
JSONA.setJsonApi(it)
logger.info(
"JSONA Using {}", it.javaClass.name
)
set = { throw JsonException("JSON API set method is not allowed.") })
.also {
logger.info("JsonApi Bean Auto Configuration Success")
try {
JSONA.getJsonApi()
} catch (_: NullPointerException) {
JSONA.setJsonApi(it)
logger.info(
"JSONA Using {}", it.javaClass.name
)
}
}
}
}
}
@@ -13,10 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ProjectName FastBaseMapper.kt
* ModuleName mingli-utils.main
* CurrentFile JacksonAutoConfiguration.kt
* LastUpdate 2026-10-02 16:10:53
* CurrentFile JacksonJsonApiAutoConfiguration.kt
* LastUpdate 2026-10-26 23:22:18
* UpdateUser MingLiPro
*/
@@ -26,9 +26,6 @@ import com.fasterxml.jackson.databind.ObjectMapper
import com.mingliqiye.utils.json.api.JSONA
import com.mingliqiye.utils.json.api.JacksonJsonApi
import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.json.converters.DateTimeJsonConverter
import com.mingliqiye.utils.json.converters.UUIDJsonConverter
import com.mingliqiye.utils.json.converters.base.addJsonConverter
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import org.slf4j.Logger
import org.springframework.boot.autoconfigure.AutoConfigureAfter
@@ -37,28 +34,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Primary
/*
* 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 JacksonAutoConfiguration.kt
* LastUpdate 2026-02-05 10:39:54
* UpdateUser MingLiPro
*/
/*
* JacksonAutoConfiguration 是一个 Spring Boot 自动配置类,用于配置 Jackson 相关的序列化和反序列化功能。
* 该类在检测到 ObjectMapper 和 Spring Boot 的 JacksonAutoConfiguration 存在时自动生效,
@@ -67,21 +42,15 @@ import org.springframework.context.annotation.Primary
* @param objectMapper 用于 JSON 序列化和反序列化的 ObjectMapper 实例。
*/
@ConditionalOnClass(name = ["com.fasterxml.jackson.databind.ObjectMapper", "org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration"])
@AutoConfigureAfter(name = ["org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration"])
open class JacksonAutoConfiguration(objectMapper: ObjectMapper) {
private val log: Logger = MingLiLoggerFactory.getLogger("MingliUtils-JacksonAutoConfiguration")
@AutoConfigureAfter(name = ["com.mingliqiye.utils.springboot.autoconfigure.JacksonJsonAutoConfiguration"])
open class JacksonJsonApiAutoConfiguration {
/*
* 初始化块:在类实例化时执行。
* 注册自定义的 UUID 和 DateTime JSON 转换器模块到 ObjectMapper 中。
*/
init {
objectMapper
.addJsonConverter<UUIDJsonConverter>()
.addJsonConverter<DateTimeJsonConverter>()
log.info("MingliUtils Jackson Serializers created")
companion object {
private val log: Logger = MingLiLoggerFactory.getLogger("MingliUtils-JacksonAutoConfiguration")
}
/*
* 创建并返回一个 JsonApi Bean 实例。
* 该方法会在没有其他 JsonApi Bean 存在时被调用,并将创建的 JacksonJsonApi 实例设置为全局默认的 JSON API。
@@ -0,0 +1,75 @@
/*
* 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 FastBaseMapper.kt
* ModuleName mingli-utils.main
* CurrentFile JacksonJsonAutoConfiguration.kt
* LastUpdate 2026-10-26 23:22:18
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure
import com.fasterxml.jackson.databind.ObjectMapper
import com.mingliqiye.utils.json.converters.DateTimeJsonConverter
import com.mingliqiye.utils.json.converters.UUIDJsonConverter
import com.mingliqiye.utils.json.converters.base.getJacksonModule
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import org.springframework.boot.autoconfigure.AutoConfigureAfter
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer
/**
* Jackson 2 的序列化模块自动配置(过渡兼容)。
*
* 在类路径存在 Jackson 2(`com.fasterxml.jackson.databind.ObjectMapper`)
* 及对应 Spring Boot 自动配置时生效,向容器注册用于追加 UUID / 日期时间
* 模块的 [Jackson2ObjectMapperBuilderCustomizer]。
*
* ## 定位说明
*
* Spring Boot 4 起默认 JSON 库为 Jackson 3,Jackson 2 的自动配置已被弃用,
* 仅用于迁移过渡,并计划在未来版本移除。本类只服务于仍在使用 Jackson 2 的场景,
* 新项目应优先使用 Jackson 3 的对应配置。
*
* ## 类名注意
*
* 条件与排序中引用的自动配置类名需与目标 Spring Boot 版本一致。
* Spring Boot 4 中 Jackson 2 的自动配置类位于 `spring-boot-jackson2` 模块
* (包路径形如 `org.springframework.boot.jackson2.autoconfigure.Jackson2AutoConfiguration`)。
* 若项目中引用的类名不存在,本配置会被整体跳过而不报错,需自行核对。
*
* ## Bean 命名
*
* 与 Jackson 3 配置中的定制器 Bean 名称刻意区分(后缀 `2`),
* 避免两套配置同时生效时发生名称冲突。
*
* @see Jackson2ObjectMapperBuilderCustomizer
*/
@ConditionalOnClass(name = ["com.fasterxml.jackson.databind.ObjectMapper", "org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration"])
@AutoConfigureAfter(name = ["org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration"])
open class JacksonJsonAutoConfiguration(objectMapper: ObjectMapper) {
companion object {
private val log = MingLiLoggerFactory.getLogger<JacksonJsonAutoConfiguration>()
}
init {
objectMapper.registerModule(DateTimeJsonConverter.getJsonConverter().getJacksonModule())
objectMapper.registerModule(UUIDJsonConverter.getJsonConverter().getJacksonModule())
log.info("MingliUtils JacksonModule UUID,DateTime Serializers created")
}
}
@@ -13,18 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ProjectName FastBaseMapper.kt
* ModuleName mingli-utils.main
* CurrentFile Okhttp3AutoConfiguration.kt
* LastUpdate 2026-10-02 16:10:15
* LastUpdate 2026-10-26 23:22:18
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import com.mingliqiye.utils.springboot.autoconfigure.builder.OkhttpBuilder
import org.slf4j.Logger
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.ObjectProvider
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
@@ -32,43 +33,91 @@ import org.springframework.context.annotation.Bean
import org.springframework.context.event.ContextClosedEvent
import org.springframework.context.event.EventListener
/**
* OkHttp 3 的 Spring Boot 自动配置。
*
* 在类路径存在 `okhttp3.OkHttpClient` 时生效,向容器注册一个默认的
* [okhttp3.OkHttpClient] Bean。构建过程中会依次应用容器中所有
* [OkhttpBuilder] 定制器(按 `@Order` / [org.springframework.core.Ordered] 排序),
* 便于调用方追加拦截器、超时、代理、连接池等配置,而无需自行创建客户端。
*
* ## 覆盖方式
*
* 若调用方需要完全自定义客户端,只需自行声明一个 [okhttp3.OkHttpClient] Bean,
* 本配置的 `@ConditionalOnMissingBean` 将自动跳过创建,不会产生多余实例。
*
* 若只想在默认客户端上做增量调整,实现 [OkhttpBuilder] 并注册为 Bean 即可,
* 无需替换整个客户端。
*
* ## 生命周期
*
* 由本配置创建的客户端会在 Spring 上下文关闭时([ContextClosedEvent])
* 主动清理连接池并关闭分发器线程池,避免线程与连接泄漏。
* 调用方自行声明的客户端不会被本配置清理,其生命周期由调用方负责。
*
* @see OkhttpBuilder
*/
@AutoConfiguration
@ConditionalOnClass(name = ["okhttp3.OkHttpClient"])
open class Okhttp3AutoConfiguration {
private var okHttpClient: okhttp3.OkHttpClient? = null
val log: Logger = MingLiLoggerFactory.getLogger<Okhttp3AutoConfiguration>()
@Autowired(required = false)
open var userDefinedBuilder: okhttp3.OkHttpClient.Builder? = null
open fun initOkHttpClient() {
okHttpClient = if (userDefinedBuilder == null) {
okhttp3.OkHttpClient()
} else {
userDefinedBuilder!!.build()
}
companion object {
val log: Logger = MingLiLoggerFactory.getLogger<Okhttp3AutoConfiguration>()
}
/**
* 由本配置创建并注册的 [okhttp3.OkHttpClient] 实例,供上下文关闭时清理使用。
*
* 当调用方自行声明了 `OkHttpClient` Bean 时,本配置的 Bean 方法不会执行,
* 该字段保持 `null`,关闭时的清理逻辑也会相应跳过。
*/
var okhttp: okhttp3.OkHttpClient? = null
/**
* 创建默认的 [okhttp3.OkHttpClient] Bean。
*
* 依次应用容器中所有 [OkhttpBuilder] 定制器后构建客户端。没有任何定制器时
* 也能正常构建([ObjectProvider] 允许零个元素)。
*
* 该 Bean 仅在容器中不存在其他 `OkHttpClient` 时创建;若调用方已自行声明,
* 本方法不会被调用。
*
* @param builders 容器中的 OkHttp 构建定制器,按 `@Order` 排序后依次应用
* @return 构建完成的 OkHttp 客户端
*/
@Bean
@ConditionalOnMissingBean
open fun okHttpClient(): okhttp3.OkHttpClient {
if (okHttpClient == null) {
initOkHttpClient()
open fun okHttpClient(builders: ObjectProvider<OkhttpBuilder>): okhttp3.OkHttpClient {
var connt = 0
return okhttp3.OkHttpClient.Builder().let { builder ->
var b = builder
builders.orderedStream().forEach {
b = it.customize(b)
connt++
}
b.build()
}.also {
okhttp = it
log.info("load $connt OkhttpBuilder initialized OkHttpClient successfully")
}
log.info("OkHttpClient initialized (using ${if (userDefinedBuilder != null) "user-defined" else "default"} builder)")
return okHttpClient!!
}
/**
* 在 Spring 上下文关闭时清理本配置创建的 OkHttp 客户端。
*
* 执行两步清理:
* 1. [okhttp3.ConnectionPool.evictAll] 立即关闭连接池中的空闲连接;
* 2. 关闭 [okhttp3.Dispatcher] 的线程池,中断未完成的任务。
*
* 仅当 [okhttp] 字段非空(即客户端由本配置创建)时执行;
* 调用方自行声明的客户端不会被清理。
*/
@EventListener(ContextClosedEvent::class)
open fun handleContextClosed() {
if (okHttpClient != null) {
okhttp?.let {
log.info("Context closed, cleaning up OkHttpClient...")
okHttpClient?.dispatcher?.executorService?.shutdown()
okHttpClient?.connectionPool?.evictAll()
okHttpClient?.dispatcher?.executorService?.shutdownNow()
it.connectionPool.evictAll()
it.dispatcher.executorService.shutdownNow()
}
}
}
@@ -0,0 +1,30 @@
/*
* 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 FastBaseMapper.kt
* ModuleName mingli-utils.main
* CurrentFile OkhttpBuilder.kt
* LastUpdate 2026-10-26 23:22:18
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure.builder
import okhttp3.OkHttpClient
@FunctionalInterface
fun interface OkhttpBuilder {
fun customize(builder: OkHttpClient.Builder): OkHttpClient.Builder
}