2 Commits
Author SHA1 Message Date
timi 9f7460e959 Merge pull request 'v0.0.3' (#2) from dev into master
Reviewed-on: #2
2026-02-10 10:56:12 +00:00
timi 90d4c5e5f6 Merge pull request 'v0.0.2' (#1) from dev into master
Reviewed-on: #1
2026-01-19 09:53:14 +00:00
44 changed files with 1142 additions and 1457 deletions
-2
View File
@@ -1,2 +0,0 @@
/cache
/project.local.yml
-154
View File
@@ -1,154 +0,0 @@
# the name by which the project can be referenced within Serena
project_name: "timi-spring"
# list of languages for which language servers are started; choose from:
# al bash clojure cpp csharp
# csharp_omnisharp dart elixir elm erlang
# fortran fsharp go groovy haskell
# haxe java julia kotlin lua
# markdown
# matlab nix pascal perl php
# php_phpactor powershell python python_jedi r
# rego ruby ruby_solargraph rust scala
# swift terraform toml typescript typescript_vts
# vue yaml zig
# (This list may be outdated. For the current list, see values of Language enum here:
# https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py
# For some languages, there are alternative language servers, e.g. csharp_omnisharp, ruby_solargraph.)
# Note:
# - For C, use cpp
# - For JavaScript, use typescript
# - For Free Pascal/Lazarus, use pascal
# Special requirements:
# Some languages require additional setup/installations.
# See here for details: https://oraios.github.io/serena/01-about/020_programming-languages.html#language-servers
# When using multiple languages, the first language server that supports a given file will be used for that file.
# The first language is the default language and the respective language server will be used as a fallback.
# Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored.
languages:
- java
# the encoding used by text files in the project
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
encoding: "utf-8"
# line ending convention to use when writing source files.
# Possible values: unset (use global setting), "lf", "crlf", or "native" (platform default)
# This does not affect Serena's own files (e.g. memories and configuration files), which always use native line endings.
line_ending:
# The language backend to use for this project.
# If not set, the global setting from serena_config.yml is used.
# Valid values: LSP, JetBrains
# Note: the backend is fixed at startup. If a project with a different backend
# is activated post-init, an error will be returned.
language_backend:
# whether to use project's .gitignore files to ignore files
ignore_all_files_in_gitignore: true
# advanced configuration option allowing to configure language server-specific options.
# Maps the language key to the options.
# Have a look at the docstring of the constructors of the LS implementations within solidlsp (e.g., for C# or PHP) to see which options are available.
# No documentation on options means no options are available.
ls_specific_settings: {}
# list of additional paths to ignore in this project.
# Same syntax as gitignore, so you can use * and **.
# Note: global ignored_paths from serena_config.yml are also applied additively.
ignored_paths: []
# whether the project is in read-only mode
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
# Added on 2025-04-18
read_only: false
# list of tool names to exclude.
# This extends the existing exclusions (e.g. from the global configuration)
#
# Below is the complete list of tools for convenience.
# To make sure you have the latest list of tools, and to view their descriptions,
# execute `uv run scripts/print_tool_overview.py`.
#
# * `activate_project`: Activates a project based on the project name or path.
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
# * `create_text_file`: Creates/overwrites a file in the project directory.
# * `delete_memory`: Delete a memory file. Should only happen if a user asks for it explicitly,
# for example by saying that the information retrieved from a memory file is no longer correct
# or no longer relevant for the project.
# * `edit_memory`: Replaces content matching a regular expression in a memory.
# * `execute_shell_command`: Executes a shell command.
# * `find_file`: Finds files in the given relative paths
# * `find_referencing_symbols`: Finds symbols that reference the given symbol using the language server backend
# * `find_symbol`: Performs a global (or local) search using the language server backend.
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
# * `initial_instructions`: Provides instructions Serena usage (i.e. the 'Serena Instructions Manual')
# for clients that do not read the initial instructions when the MCP server is connected.
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
# * `list_memories`: List available memories. Any memory can be read using the `read_memory` tool.
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
# * `read_file`: Reads a file within the project directory.
# * `read_memory`: Read the content of a memory file. This tool should only be used if the information
# is relevant to the current task. You can infer whether the information
# is relevant from the memory file name.
# You should not read the same memory file multiple times in the same conversation.
# * `rename_memory`: Renames or moves a memory. Moving between project and global scope is supported
# (e.g., renaming "global/foo" to "bar" moves it from global to project scope).
# * `rename_symbol`: Renames a symbol throughout the codebase using language server refactoring capabilities.
# For JB, we use a separate tool.
# * `replace_content`: Replaces content in a file (optionally using regular expressions).
# * `replace_symbol_body`: Replaces the full definition of a symbol using the language server backend.
# * `safe_delete_symbol`:
# * `search_for_pattern`: Performs a search for a pattern in the project.
# * `write_memory`: Write some information (utf-8-encoded) about this project that can be useful for future tasks to a memory in md format.
# The memory name should be meaningful.
excluded_tools: []
# list of tools to include that would otherwise be disabled (particularly optional tools that are disabled by default).
# This extends the existing inclusions (e.g. from the global configuration).
included_optional_tools: []
# fixed set of tools to use as the base tool set (if non-empty), replacing Serena's default set of tools.
# This cannot be combined with non-empty excluded_tools or included_optional_tools.
fixed_tools: []
# list of mode names to that are always to be included in the set of active modes
# The full set of modes to be activated is base_modes + default_modes.
# If the setting is undefined, the base_modes from the global configuration (serena_config.yml) apply.
# Otherwise, this setting overrides the global configuration.
# Set this to [] to disable base modes for this project.
# Set this to a list of mode names to always include the respective modes for this project.
base_modes:
# list of mode names that are to be activated by default.
# The full set of modes to be activated is base_modes + default_modes.
# If the setting is undefined, the default_modes from the global configuration (serena_config.yml) apply.
# Otherwise, this overrides the setting from the global configuration (serena_config.yml).
# This setting can, in turn, be overridden by CLI parameters (--mode).
default_modes:
# initial prompt for the project. It will always be given to the LLM upon activating the project
# (contrary to the memories, which are loaded on demand).
initial_prompt: ""
# time budget (seconds) per tool call for the retrieval of additional symbol information
# such as docstrings or parameter information.
# This overrides the corresponding setting in the global configuration; see the documentation there.
# If null or missing, use the setting from the global configuration.
symbol_info_budget:
# list of regex patterns which, when matched, mark a memory entry as read‑only.
# Extends the list from the global configuration, merging the two lists.
read_only_memory_patterns: []
# list of regex patterns for memories to completely ignore.
# Matching memories will not appear in list_memories or activate_project output
# and cannot be accessed via read_memory or write_memory.
# To access ignored memory files, use the read_file tool on the raw file path.
# Extends the list from the global configuration, merging the two lists.
# Example: ["_archive/.*", "_episodes/.*"]
ignored_memory_patterns: []
+26 -43
View File
@@ -7,22 +7,22 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.13</version>
<version>3.4.0</version>
<relativePath/>
</parent>
<groupId>com.imyeyu.spring</groupId>
<artifactId>timi-spring</artifactId>
<version>0.1.0</version>
<version>0.0.3</version>
<packaging>jar</packaging>
<properties>
<java.version>21</java.version>
<maven.test.skip>true</maven.test.skip>
<springboot.version>3.5.13</springboot.version>
<springboot.version>3.4.0</springboot.version>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.test.skip>true</maven.test.skip>
</properties>
<build>
@@ -37,42 +37,10 @@
<artifactId>maven-source-plugin</artifactId>
<version>3.3.1</version>
</plugin>
<plugin>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-maven-plugin</artifactId>
<version>1.18.20.0</version>
<configuration>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<outputDirectory>${project.build.directory}/delombok</outputDirectory>
<addOutputDirectory>false</addOutputDirectory>
<encoding>UTF-8</encoding>
</configuration>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>delombok</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.36</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.11.2</version>
<configuration>
<sourcepath>${project.build.directory}/delombok</sourcepath>
<encoding>UTF-8</encoding>
<charset>UTF-8</charset>
<docencoding>UTF-8</docencoding>
</configuration>
</plugin>
</plugins>
</build>
@@ -102,6 +70,20 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${springboot.version}</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -131,21 +113,22 @@
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.5</version>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.13.1</version>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>com.imyeyu.lang</groupId>
<artifactId>timi-lang</artifactId>
<version>0.1.0</version>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<groupId>com.imyeyu.io</groupId>
<artifactId>timi-io</artifactId>
<version>0.0.2</version>
</dependency>
</dependencies>
</project>
+75 -97
View File
@@ -1,16 +1,19 @@
package com.imyeyu.spring;
import com.imyeyu.io.IO;
import com.google.gson.Gson;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.ResultCode;
import com.imyeyu.java.bean.Language;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.java.bean.timi.TimiResponse;
import com.imyeyu.java.ref.Ref;
import com.imyeyu.lang.bean.Language;
import com.imyeyu.spring.bean.RequestRange;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.web.context.request.RequestContextHolder;
@@ -18,7 +21,8 @@ import org.springframework.web.context.request.ServletRequestAttributes;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Locale;
@@ -35,23 +39,67 @@ import java.util.Locale;
*/
public class TimiSpring {
/** 版本号 */
public static final String VERSION = "0.0.1";
private static final Logger log = LoggerFactory.getLogger(TimiSpring.class);
private static final Gson GSON = new Gson();
/**
* 工具类禁止实例化
*/
private TimiSpring() {
}
/**
* 回调数据
*
* @param response 返回
* @param resp 返回结果
*/
public static void render(HttpServletResponse response, TimiResponse<?> resp) {
try {
HttpSession session = getSession();
response.setContentType("application/json;charset=UTF-8");
OutputStream out = response.getOutputStream();
out.write(GSON.toJson(resp).getBytes(StandardCharsets.UTF_8));
out.flush();
out.close();
} catch (Exception e) {
log.error("TimiSpring.render Error", e);
}
}
/**
* 回调错误
*
* @param response 返回
* @param code 代码
* @param msgKey 消息映射键
*/
public static void renderError(HttpServletResponse response, TimiCode code, String msgKey) {
try {
response.setContentType("application/json;charset=UTF-8");
OutputStream out = response.getOutputStream();
out.write(GSON.toJson(code.toResponse().msg(msgKey)).getBytes(StandardCharsets.UTF_8));
out.flush();
out.close();
} catch (Exception e) {
log.error("TimiSpring.renderError error", e);
}
}
/**
* 获取 Servlet 请求属性
*
* @return Servlet 请求属性
* @throws ActionException 请求异常
* @throws TimiException 请求异常
*/
public static ServletRequestAttributes getServletRequestAttributes() {
if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes sra) {
return sra;
}
throw new ActionException(ResultCode.ERROR_NPE_VARIABLE);
throw new TimiException(TimiCode.ERROR_NPE_VARIABLE);
}
/**
@@ -109,7 +157,7 @@ public class TimiSpring {
*/
public static String cutURIStartAt(String flag) {
int indexOf = getURI().indexOf(flag);
ActionException.requiredTrue(-1 < indexOf, "not found flag: %s".formatted(flag));
TimiException.requiredTrue(-1 < indexOf, "not found flag: %s".formatted(flag));
return getURI().substring(indexOf + flag.length());
}
@@ -332,9 +380,9 @@ public class TimiSpring {
if (cookies == null) {
return null;
}
for (Cookie cookie : cookies) {
if (cookie.getName().equals(key)) {
return cookie;
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals(key)) {
return cookies[i];
}
}
return null;
@@ -346,16 +394,7 @@ public class TimiSpring {
* @return 令牌
*/
public static String getToken() {
return TimiJava.firstNotEmpty(getHeader("Token"), getHeader("token"), getRequestArg("Token"), getRequestArg("token"));
}
/**
* 获取请求密钥,键为 Key 或 key,包括请求头和 URI
*
* @return 密钥
*/
public static String getKey() {
return TimiJava.firstNotEmpty(getHeader("Key"), getHeader("key"), getRequestArg("Key"), getRequestArg("key"));
return TimiJava.firstNotEmpty(getHeader("Token"), getHeader("token"), getRequestArg("token"), getRequestArg("Token"));
}
/**
@@ -399,7 +438,7 @@ public class TimiSpring {
* 获取请求 IP
*
* @return 请求 IP
* @throws ActionException 服务异常
* @throws TimiException 服务异常
*/
public static String getRequestIP() {
String ip = getHeader("x-forwarded-for");
@@ -430,70 +469,30 @@ public class TimiSpring {
/**
* 解析 Range 请求范围
*
* @param total 总数据量
* @param fileLength 文件长度
* @return 请求范围
* @throws IOException IO 异常
*/
public static RequestRange getRequestRange(long total) throws IOException {
public static RequestRange requestRange(long fileLength) throws IOException {
HttpServletResponse resp = getResponse();
String range = getHeader("Range");
if (TimiJava.isEmpty(range)) {
return null;
}
range = range.trim();
if (!range.startsWith("bytes=")) {
return null;
}
String rangeValue = range.substring("bytes=".length()).trim();
int separatorIndex = rangeValue.indexOf('-');
// 当前实现只接受单个字节范围,不处理 multipart/byteranges
if (separatorIndex < 0 || rangeValue.indexOf(',', separatorIndex + 1) != -1) {
resp.setHeader("Content-Range", "bytes */" + total);
resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
String startText = rangeValue.substring(0, separatorIndex).trim();
String endText = rangeValue.substring(separatorIndex + 1).trim();
if (total <= 0) {
resp.setHeader("Content-Range", "bytes */" + total);
resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
long start;
long end;
try {
if (TimiJava.isEmpty(startText)) {
if (TimiJava.isEmpty(endText)) {
resp.setHeader("Content-Range", "bytes */" + total);
resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
// `bytes=-500` 表示请求文件末尾 500 字节
long suffixLength = Long.parseLong(endText);
if (suffixLength <= 0) {
resp.setHeader("Content-Range", "bytes */" + total);
resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
start = Math.max(0, total - suffixLength);
end = total - 1;
} else {
// `bytes=97043805-` 表示从指定起点一直读到文件结尾
start = Long.parseLong(startText);
end = TimiJava.isEmpty(endText) ? total - 1 : Long.parseLong(endText);
}
} catch (NumberFormatException exception) {
resp.setHeader("Content-Range", "bytes */" + total);
resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
String range = getRequestAttrAsString("Range");
if (range == null || !range.startsWith("bytes=")) {
return null;
}
// 处理 bytes=0-999 格式
String rangeValue = range.substring("bytes=".length());
String[] ranges = rangeValue.split("-");
TimiException.requiredTrue(2 == ranges.length, "Invalid Range format");
long start = Long.parseLong(ranges[0]);
long end = ranges[1].isEmpty() ? fileLength - 1 : Long.parseLong(ranges[1]);
// 验证范围有效性
if (start < 0 || total <= end || end < start) {
resp.setHeader("Content-Range", "bytes */" + total);
if (start < 0 || fileLength <= end || end < start) {
resp.setHeader("Content-Range", "bytes */" + fileLength);
resp.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return null;
}
return new RequestRange(start, end, total);
return new RequestRange(start, end);
}
public static void copyPropertiesNotNull(Object source, Object target) {
@@ -508,25 +507,4 @@ public class TimiSpring {
}
}
}
public static void responseRangeStream(InputStream stream, long total) throws IOException {
HttpServletResponse resp = getResponse();
RequestRange range = getRequestRange(total);
if (range == null && resp.isCommitted()) {
return;
}
if (range == null) {
// 完整文件
resp.setContentLengthLong(total);
resp.setStatus(HttpServletResponse.SC_OK);
IO.toOutputStream(stream, resp.getOutputStream());
} else {
// 分片文件
resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
resp.setHeader("Content-Range", "bytes %s-%s/%s".formatted(range.getStart(), range.getEnd(), range.getTotal()));
resp.setContentLengthLong(range.getLength());
IO.toOutputStream(stream, resp.getOutputStream(), range.getStart(), range.getEnd());
resp.flushBuffer();
}
}
}
@@ -38,7 +38,7 @@ public class AOPLogInterceptor {
}
/** 注入注解 */
@Pointcut("@annotation(com.imyeyu.spring.annotation.AOPLog)")
@Pointcut("@annotation(annotation.com.imyeyu.spring.AOPLog)")
public void logPointCut() {
}
@@ -63,45 +63,41 @@ public class AOPLogInterceptor {
@AfterReturning(returning = "response", pointcut = "logPointCut()")
public void doAfterReturning(Object response) throws Throwable {
String msg = "ID: {} Response <- Return.";
switch (response) {
case IDEntity<?> entity ->
// 返回实体
msg += entity.getClass().getSimpleName() + "." + entity.getId();
case PageResult<?> pageResult -> {
// 返回数组
if (pageResult.getList().isEmpty()) {
msg += "PageResult<?> Empty";
if (response instanceof IDEntity<?> entity) {
// 返回实体
msg += entity.getClass().getSimpleName() + "." + entity.getId();
} else if (response instanceof PageResult<?> pageResult) {
// 返回数组
if (pageResult.getList().isEmpty()) {
msg += "PageResult<?> Empty";
} else {
if (pageResult.getList().get(0) == null) {
msg += "PageResult<?>." + pageResult.getList().size();
} else {
if (pageResult.getList().getFirst() == null) {
msg += "PageResult<?>." + pageResult.getList().size();
} else {
msg += "PageResult<%s>[%s]".formatted(pageResult.getList().getFirst().getClass().getSimpleName(), pageResult.getList().size());
}
msg += "PageResult<" + pageResult.getList().get(0).getClass().getSimpleName() + ">[" + pageResult.getList().size() + "]";
}
// 返回数据页
}
case String string -> {
// 返回字符串
if (string.length() < 64) {
msg += string;
} else {
msg += string.substring(0, 64) + "..";
}
msg = msg.replaceAll("[\\r\\n]+", "");
// 返回数据页
} else if (response instanceof String string) {
// 返回字符串
if (string.length() < 64) {
msg += string;
} else {
msg += string.substring(0, 64) + "..";
}
case Boolean bool ->
// 返回布尔值
msg += bool;
case Number number ->
// 返回数字
msg += response.getClass().getSimpleName() + ".[" + number.doubleValue() + "]";
case null, default -> {
// 其他对象
if (TimiJava.isNotEmpty(response)) {
msg += response.getClass().getSimpleName();
} else {
msg += "NULL";
}
msg = msg.replaceAll("[\\r\\n]+", "");
} else if (response instanceof Boolean bool) {
// 返回布尔值
msg += bool;
} else if (response instanceof Number number) {
// 返回数字
msg += response.getClass().getSimpleName() + ".[" + number.doubleValue() + "]";
} else {
// 其他对象
if (TimiJava.isNotEmpty(response)) {
msg += response.getClass().getSimpleName();
} else {
msg += "NULL";
}
}
log.info(msg, TimiSpring.getSessionAttr(REQUEST_ID));
@@ -41,8 +41,8 @@ public abstract class CaptchaValidAbstractInterceptor {
}
if (joinPoint.getSignature() instanceof MethodSignature ms) {
Object[] args = joinPoint.getArgs();
for (Object arg : args) {
if (arg instanceof CaptchaData<?> captchaData) {
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof CaptchaData<?> captchaData) {
// 校验请求参数的验证码
verify(captchaData.getCaptchaId(), captchaData.getCaptcha());
break;
@@ -1,31 +0,0 @@
package com.imyeyu.spring.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 标记需要在响应阶段自动回填的多语言字段
*
* @author 夜雨
* @since 2026-07-17 00:00
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MultilingualField {
/**
* 多语言 ID 来源字段名
*
* @return 来源字段名
*/
String value();
/**
* 模板参数来源字段名
*
* @return 同类中的 Map 字段名
*/
String argMap() default "";
}
@@ -1,43 +0,0 @@
package com.imyeyu.spring.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 读取 JSON 请求体中的单个字段并绑定到接口参数。
*
* <p>默认使用方法参数名作为 JSON 字段名,也可以手动指定字段名。
*
* <pre>
* public void run(@RequestBodyValue String data) {
* }
*
* public void run(@RequestBodyValue("value") Long id) {
* }
* </pre>
*
* @author 夜雨
* @version 2026-04-08 11:00
*/
@Documented
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestBodyValue {
/**
* JSON 字段名,为空时使用方法参数名。
*
* @return JSON 字段名
*/
String value() default "";
/**
* 是否必须存在该字段。
*
* @return true 表示必须存在
*/
boolean required() default true;
}
@@ -1,82 +0,0 @@
package com.imyeyu.spring.annotation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.ResultCode;
import com.imyeyu.java.bean.ActionException;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.MethodParameter;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* {@link RequestBodyValue} 参数解析器。
*
* @author 夜雨
* @version 2026-04-08 11:00
*/
@Component
public class RequestBodyValueArgumentResolver implements HandlerMethodArgumentResolver {
private static final String REQUEST_BODY_JSON_NODE_ATTR = RequestBodyValueArgumentResolver.class.getName() + ".REQUEST_BODY_JSON_NODE";
private final ObjectMapper objectMapper;
/**
* 创建 {@link RequestBodyValue} 参数解析器。
*
* @param objectMapper Jackson 对象映射器
*/
public RequestBodyValueArgumentResolver(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public boolean supportsParameter(@NonNull MethodParameter parameter) {
return parameter.hasParameterAnnotation(RequestBodyValue.class);
}
@Override
public Object resolveArgument(@NonNull MethodParameter parameter, ModelAndViewContainer mavContainer, @NonNull NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
RequestBodyValue bodyValue = parameter.getParameterAnnotation(RequestBodyValue.class);
if (bodyValue == null) {
return null;
}
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
ActionException.required(request, "not found request");
assert request != null;
JsonNode requestBody;
{
Object cached = request.getAttribute(REQUEST_BODY_JSON_NODE_ATTR);
if (cached instanceof JsonNode jsonNode) {
return jsonNode;
}
byte[] bodyBytes = request.getInputStream().readAllBytes();
ActionException.requiredTrue(1 < bodyBytes.length, "empty request body");
requestBody = objectMapper.readTree(bodyBytes);
ActionException.requiredTrue(requestBody != null && requestBody.isObject(), "not object request body");
request.setAttribute(REQUEST_BODY_JSON_NODE_ATTR, requestBody);
}
String fieldName = bodyValue.value();
{
if (TimiJava.isEmpty(fieldName)) {
fieldName = parameter.getParameterName();
}
ActionException.required(fieldName, "not found @RequestBodyValue parameter name");
}
JsonNode fieldNode = requestBody.get(fieldName);
if (fieldNode == null || fieldNode.isMissingNode() || fieldNode.isNull()) {
if (!bodyValue.required()) {
return null;
}
throw new ActionException(ResultCode.ARG_MISS, "not found json field: %s".formatted(fieldName));
}
return objectMapper.treeToValue(fieldNode, parameter.getParameterType());
}
}
@@ -10,7 +10,7 @@ import java.lang.annotation.Target;
/**
* 应用在 Controller 的接口上
*
* <p>{@link #inSeconds()} 生命周期内(秒)限制访问 {@link #value()} 次
* <p>{@link #lifeCycle()} 生命周期内(秒)限制访问 {@link #value()} 次
*
* @author 夜雨
* @version 2021-08-16 17:57
@@ -32,5 +32,5 @@ public @interface RequestRateLimit {
*
* @return 生命周期秒数
*/
int inSeconds() default 10;
int lifeCycle() default 10;
}
@@ -2,7 +2,6 @@ package com.imyeyu.spring.annotation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NoArgsConstructor;
import org.springframework.lang.NonNull;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
@@ -13,9 +12,14 @@ import org.springframework.web.servlet.HandlerInterceptor;
* @author 夜雨
* @version 2021-08-16 18:07
*/
@NoArgsConstructor
public abstract class RequestRateLimitAbstractInterceptor implements HandlerInterceptor {
/**
* 创建访问频率限制拦截器
*/
protected RequestRateLimitAbstractInterceptor() {
}
/**
* 构建接口标识
*
@@ -45,7 +49,7 @@ public abstract class RequestRateLimitAbstractInterceptor implements HandlerInte
return true;
}
// 频率限制
return beforeRun(req, resp, buildId(handlerMethod), requestRateLimit.inSeconds(), requestRateLimit.value());
return beforeRun(req, resp, buildId(handlerMethod), requestRateLimit.lifeCycle(), requestRateLimit.value());
}
return true;
}
@@ -0,0 +1,22 @@
package com.imyeyu.spring.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 单字段 Json 数据体
*
* @author 夜雨
* @version 2023-08-09 10:36
* @deprecated 0.0.3 过时,0.0.5 移除,单参数建议 url 传参
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Deprecated
public @interface RequestSingleParam {
}
@@ -0,0 +1,67 @@
package com.imyeyu.spring.annotation;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import jakarta.annotation.Nonnull;
import jakarta.servlet.http.HttpServletRequest;
import com.imyeyu.io.IO;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* 单参数请求解析器
*
* @author 夜雨
* @since 2025-10-13 16:29
* @deprecated 0.0.3 过时,0.0.5 移除,单参数建议 url 传参
*/
@Component
@Deprecated
public class RequestSingleParamResolver implements HandlerMethodArgumentResolver {
/**
* 创建单参数解析器
*/
public RequestSingleParamResolver() {
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(RequestSingleParam.class);
}
@Override
public Object resolveArgument(@Nonnull MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
if (request == null) {
throw new TimiException(TimiCode.REQUEST_BAD, "request illegal");
}
JsonElement element = JsonParser.parseString(IO.toString(request.getInputStream()));
if (!element.isJsonObject()) {
throw new TimiException(TimiCode.ARG_BAD, "not json object");
}
JsonObject object = element.getAsJsonObject();
String parameterName = parameter.getParameterName();
if (!object.has(parameterName)) {
throw new TimiException(TimiCode.ARG_MISS, "not found " + parameterName + " param");
}
JsonElement el = object.get(parameterName);
if (parameter.getParameterType().isAssignableFrom(Long.class)) {
return el.getAsLong();
}
if (parameter.getParameterType().isAssignableFrom(Integer.class)) {
return el.getAsInt();
}
if (parameter.getParameterType().isAssignableFrom(String.class)) {
return el.getAsString();
}
throw new TimiException(TimiCode.ERROR, "not support parameter type");
}
}
@@ -1,7 +1,6 @@
package com.imyeyu.spring.bean;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
/**
* 含验证码数据实体
@@ -10,7 +9,6 @@ import lombok.Data;
* @author 夜雨
* @version 2021-03-01 17:10
*/
@Data
public class CaptchaData<T> {
/** 来源 */
@@ -23,4 +21,64 @@ public class CaptchaData<T> {
/** 数据体 */
protected T data;
/**
* 创建验证码数据实体
*/
public CaptchaData() {
}
/**
* 获取验证码 ID
*
* @return 验证码 ID
*/
public String getCaptchaId() {
return captchaId;
}
/**
* 设置验证码 ID
*
* @param captchaId 验证码 ID
*/
public void setCaptchaId(String captchaId) {
this.captchaId = captchaId;
}
/**
* 获取验证码
*
* @return 验证码
*/
public String getCaptcha() {
return captcha;
}
/**
* 设置验证码
*
* @param captcha 验证码
*/
public void setCaptcha(String captcha) {
this.captcha = captcha;
}
/**
* 获取数据体
*
* @return 数据体
*/
public T getData() {
return data;
}
/**
* 设置数据体
*
* @param data 数据体
*/
public void setData(T data) {
this.data = data;
}
}
@@ -0,0 +1,93 @@
package com.imyeyu.spring.bean;
import com.imyeyu.java.bean.Language;
import com.imyeyu.java.ref.Ref;
import com.imyeyu.spring.annotation.table.AutoUUID;
import com.imyeyu.spring.annotation.table.Id;
import com.imyeyu.spring.entity.Creatable;
import com.imyeyu.spring.entity.Deletable;
import com.imyeyu.spring.entity.IDEntity;
import com.imyeyu.spring.entity.Updatable;
/**
* 多语言实体基类
*
* @author 夜雨
* @since 2025-10-17 15:21
*/
public class Multilingual extends Language implements IDEntity<String>, Creatable, Updatable, Deletable {
/** 唯一标识 */
@Id
@AutoUUID
protected String id;
/** 创建时间 */
protected Long createdAt;
/** 更新时间 */
protected Long updatedAt;
/** 删除时间 */
protected Long deletedAt;
/**
* 创建多语言实体
*/
public Multilingual() {
}
/**
* 获取指定语言值
*
* @param language 指定语言
* @return 值
*/
public String getValue(Language.Enum language) {
try {
return Ref.getFieldValue(this, language.toString().replace("_", ""), String.class);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
@Override
public Long getCreatedAt() {
return createdAt;
}
@Override
public void setCreatedAt(Long createdAt) {
this.createdAt = createdAt;
}
@Override
public Long getUpdatedAt() {
return updatedAt;
}
@Override
public void setUpdatedAt(Long updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public Long getDeletedAt() {
return deletedAt;
}
@Override
public void setDeletedAt(Long deletedAt) {
this.deletedAt = deletedAt;
}
}
+124 -6
View File
@@ -4,9 +4,6 @@ import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.BasePage;
import com.imyeyu.spring.mapper.BaseMapper;
import com.imyeyu.utils.Text;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import java.util.LinkedHashMap;
@@ -17,9 +14,6 @@ import java.util.LinkedHashMap;
* @author 夜雨
* @version 2023-06-02 14:47
*/
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Page<T> extends BasePage {
/** 精确匹配示例 */
@@ -37,6 +31,130 @@ public class Page<T> extends BasePage {
/** 排序字段映射 */
protected LinkedHashMap<String, BaseMapper.OrderType> orderMap;
/**
* 创建分页参数
*/
public Page() {
}
/**
* 创建分页参数
*
* @param index 页码
* @param size 每页数量
*/
public Page(int index, int size) {
super(index, size);
}
/**
* 获取偏移量
*
* @return 偏移量
*/
public long getOffset() {
return (long) index * size;
}
/**
* 获取限制数量
*
* @return 限制数量
*/
public long getLimit() {
return size;
}
/**
* 获取精确匹配示例
*
* @return 精确匹配示例
*/
public T getEqualsExample() {
return equalsExample;
}
/**
* 设置精确匹配示例
*
* @param equalsExample 精确匹配示例
*/
public void setEqualsExample(T equalsExample) {
this.equalsExample = equalsExample;
}
/**
* 获取模糊匹配示例
*
* @return 模糊匹配示例
*/
public T getLikesExample() {
return likesExample;
}
/**
* 设置模糊匹配示例
*
* @param likesExample 模糊匹配示例
*/
public void setLikesExample(T likesExample) {
this.likesExample = likesExample;
}
/**
* 获取精确匹配连接逻辑
*
* @return 连接逻辑
*/
public Logic getEqualsLogic() {
return equalsLogic;
}
/**
* 设置精确匹配连接逻辑
*
* @param equalsLogic 连接逻辑
*/
public void setEqualsLogic(Logic equalsLogic) {
this.equalsLogic = equalsLogic;
}
/**
* 获取模糊匹配连接逻辑
*
* @return 连接逻辑
*/
public Logic getLikesLogic() {
return likesLogic;
}
/**
* 设置模糊匹配连接逻辑
*
* @param likesLogic 连接逻辑
*/
public void setLikesLogic(Logic likesLogic) {
this.likesLogic = likesLogic;
}
/**
* 获取排序映射
*
* @return 排序映射
*/
public LinkedHashMap<String, BaseMapper.OrderType> getOrderMap() {
return orderMap;
}
/**
* 设置排序映射
*
* @param orderMap 排序映射
*/
public void setOrderMap(LinkedHashMap<String, BaseMapper.OrderType> orderMap) {
this.orderMap = orderMap;
}
/**
* 添加排序字段
*
@@ -11,4 +11,9 @@ import com.imyeyu.java.bean.BasePageResult;
*/
public class PageResult<T> extends BasePageResult<T> {
/**
* 创建分页结果
*/
public PageResult() {
}
}
@@ -1,16 +1,19 @@
package com.imyeyu.spring.bean;
import lombok.Data;
/**
* RedisConfig 配置参数
*
* @author 夜雨
* @version 2021-11-21 10:02
*/
@Data
public class RedisConfigParams {
/**
* 创建 Redis 配置参数
*/
public RedisConfigParams() {
}
/** 地址 */
private String host;
@@ -32,4 +35,129 @@ public class RedisConfigParams {
/** 最大空闲连接 */
private int maxIdle;
/**
* 获取地址
*
* @return 地址
*/
public String getHost() {
return host;
}
/**
* 设置地址
*
* @param host 地址
*/
public void setHost(String host) {
this.host = host;
}
/**
* 获取端口
*
* @return 端口
*/
public int getPort() {
return port;
}
/**
* 设置端口
*
* @param port 端口
*/
public void setPort(int port) {
this.port = port;
}
/**
* 获取密码
*
* @return 密码
*/
public String getPassword() {
return password;
}
/**
* 设置密码
*
* @param password 密码
*/
public void setPassword(String password) {
this.password = password;
}
/**
* 获取超时(毫秒)
*
* @return 超时(毫秒)
*/
public int getTimeout() {
return timeout;
}
/**
* 设置超时(毫秒)
*
* @param timeout 超时(毫秒)
*/
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* 获取最大活跃连接
*
* @return 最大活跃连接
*/
public int getMaxActive() {
return maxActive;
}
/**
* 设置最大活跃连接
*
* @param maxActive 最大活跃连接
*/
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
/**
* 获取最小空闲连接
*
* @return 最小空闲连接
*/
public int getMinIdle() {
return minIdle;
}
/**
* 设置最小空闲连接
*
* @param minIdle 最小空闲连接
*/
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
/**
* 获取最大空闲连接
*
* @return 最大空闲连接
*/
public int getMaxIdle() {
return maxIdle;
}
/**
* 设置最大空闲连接
*
* @param maxIdle 最大空闲连接
*/
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
}
@@ -1,18 +1,11 @@
package com.imyeyu.spring.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 请求范围参数
*
* @author 夜雨
* @since 2025-07-14 17:09
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RequestRange {
/** 起始值 */
@@ -21,8 +14,52 @@ public class RequestRange {
/** 结束值 */
private long end;
/** 总数据量 */
private long total;
/**
* 创建请求范围
*
* @param start 起始值
* @param end 结束值
*/
public RequestRange(long start, long end) {
this.start = start;
this.end = end;
}
/**
* 获取起始值
*
* @return 起始值
*/
public long getStart() {
return start;
}
/**
* 设置起始值
*
* @param start 起始值
*/
public void setStart(long start) {
this.start = start;
}
/**
* 获取结束值
*
* @return 结束值
*/
public long getEnd() {
return end;
}
/**
* 设置结束值
*
* @param end 结束值
*/
public void setEnd(long end) {
this.end = end;
}
/**
* 获取范围长度
@@ -2,7 +2,6 @@ package com.imyeyu.spring.config;
import com.imyeyu.spring.bean.RedisConfigParams;
import com.imyeyu.spring.util.Redis;
import io.lettuce.core.api.StatefulConnection;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.interceptor.KeyGenerator;
@@ -40,7 +39,7 @@ public abstract class AbstractRedisConfig implements CachingConfigurer {
* 连接池配置
* <p>参考:
* <pre>
* GenericObjectPoolConfig&lt;StatefulConnection&lt;?, ?&gt;&gt; config = new GenericObjectPoolConfig&lt;&gt;();
* GenericObjectPoolConfig&lt;?&gt; config = new GenericObjectPoolConfig&lt;&gt;();
* config.setMaxTotal(config.getMaxActive());
* config.setMinIdle(config.getMinIdle());
* config.setMaxIdle(config.getMaxIdle());
@@ -49,7 +48,7 @@ public abstract class AbstractRedisConfig implements CachingConfigurer {
*
* @return GenericObjectPoolConfig
*/
public abstract GenericObjectPoolConfig<StatefulConnection<?, ?>> getPoolConfig();
public abstract GenericObjectPoolConfig<?> getPoolConfig();
/**
* Redis key 生成策略
@@ -1,10 +1,7 @@
package com.imyeyu.spring.entity;
import com.fasterxml.jackson.annotation.JsonView;
import com.imyeyu.spring.annotation.table.DeleteColumn;
import com.imyeyu.spring.util.ResponseView;
import com.imyeyu.utils.Time;
import lombok.Data;
import java.io.Serializable;
@@ -14,23 +11,78 @@ import java.io.Serializable;
* @author 夜雨
* @version 2021-11-20 17:45
*/
@Data
public class BaseEntity implements Serializable, Creatable, Updatable, Deletable {
/**
* 创建基础实体
*/
public BaseEntity() {
}
/** 创建时间 */
@JsonView(ResponseView.Public.class)
protected Long createdAt;
/** 更新时间 */
@JsonView(ResponseView.Public.class)
protected Long updatedAt;
/** 删除时间 */
@DeleteColumn
@JsonView(ResponseView.Admin.class)
protected Long deletedAt;
@JsonView(ResponseView.Admin.class)
/**
* 获取创建时间
*
* @return 创建时间
*/
public Long getCreatedAt() {
return createdAt;
}
/**
* 设置创建时间
*
* @param createdAt 创建时间
*/
public void setCreatedAt(Long createdAt) {
this.createdAt = createdAt;
}
/**
* 获取更新时间
*
* @return 更新时间
*/
public Long getUpdatedAt() {
return updatedAt;
}
/**
* 设置更新时间
*
* @param updatedAt 更新时间
*/
public void setUpdatedAt(Long updatedAt) {
this.updatedAt = updatedAt;
}
/**
* 获取删除时间
*
* @return 删除时间
*/
public Long getDeletedAt() {
return deletedAt;
}
/**
* 设置删除时间
*
* @param deletedAt 删除时间
*/
public void setDeletedAt(Long deletedAt) {
this.deletedAt = deletedAt;
}
@Override
public boolean isDeleted() {
return deletedAt != null && deletedAt < Time.now();
@@ -1,10 +1,6 @@
package com.imyeyu.spring.entity;
import com.fasterxml.jackson.annotation.JsonView;
import com.imyeyu.spring.annotation.table.Id;
import com.imyeyu.spring.util.ResponseView;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 基本长整型 ID 实体
@@ -12,12 +8,33 @@ import lombok.EqualsAndHashCode;
* @author 夜雨
* @since 2025-02-07 12:51
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class Entity extends BaseEntity implements IDEntity<Long> {
/** ID */
@Id
@JsonView(ResponseView.Public.class)
protected Long id;
/**
* 创建基础 ID 实体
*/
public Entity() {
}
/**
* 获取 ID
*
* @return ID
*/
public Long getId() {
return id;
}
/**
* 设置 ID
*
* @param id ID
*/
public void setId(Long id) {
this.id = id;
}
}
@@ -1,43 +0,0 @@
package com.imyeyu.spring.entity;
import com.fasterxml.jackson.annotation.JsonView;
import com.imyeyu.lang.bean.Language;
import com.imyeyu.lang.bean.MultilingualValue;
import com.imyeyu.spring.annotation.table.AutoUUID;
import com.imyeyu.spring.annotation.table.Id;
import com.imyeyu.spring.util.ResponseView;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 多语言实体基类
*
* @author 夜雨
* @since 2025-10-17 15:21
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class Multilingual extends Language implements MultilingualValue, IDEntity<String>, Creatable, Updatable, Deletable, Destroyable {
/** 唯一标识 */
@Id
@AutoUUID
@JsonView(ResponseView.Public.class)
protected String id;
/** 业务类型 */
@JsonView(ResponseView.Public.class)
protected String bizType;
/** 创建时间 */
@JsonView(ResponseView.Admin.class)
protected Long createdAt;
/** 更新时间 */
@JsonView(ResponseView.Admin.class)
protected Long updatedAt;
/** 删除时间 */
@JsonView(ResponseView.Admin.class)
protected Long deletedAt;
}
@@ -1,11 +1,7 @@
package com.imyeyu.spring.entity;
import com.fasterxml.jackson.annotation.JsonView;
import com.imyeyu.spring.annotation.table.AutoUUID;
import com.imyeyu.spring.annotation.table.Id;
import com.imyeyu.spring.util.ResponseView;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 基本 UUID 实体
@@ -13,13 +9,24 @@ import lombok.EqualsAndHashCode;
* @author 夜雨
* @since 2025-02-07 12:07
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class UUIDEntity extends BaseEntity implements IDEntity<String> {
/** ID */
@Id
@AutoUUID
@JsonView(ResponseView.Public.class)
protected String id;
/**
* 创建 UUID 实体
*/
public UUIDEntity() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
@@ -0,0 +1,63 @@
package com.imyeyu.spring.handler;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.imyeyu.java.TimiJava;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* MySQL JSON 数据类型处理器
*
* @author 夜雨
* @since 2021-07-04 09:36
*/
public class GsonHandler extends BaseTypeHandler<JsonElement> {
/**
* 创建 Gson 类型处理器
*/
public GsonHandler() {
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, JsonElement parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter.toString());
}
@Override
public JsonElement getNullableResult(ResultSet rs, String columnName) throws SQLException {
return toElement(rs.getString(columnName));
}
@Override
public JsonElement getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return toElement(rs.getString(columnIndex));
}
@Override
public JsonElement getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return toElement(cs.getNString(columnIndex));
}
private JsonElement toElement(String json) {
if (TimiJava.isNotEmpty(json)) {
JsonElement el = JsonParser.parseString(json);
if (el.isJsonObject()) {
return el.getAsJsonObject();
}
if (el.isJsonArray()) {
return el.getAsJsonArray();
}
if (el.isJsonPrimitive()) {
return el.getAsJsonPrimitive();
}
}
return null;
}
}
@@ -1,62 +0,0 @@
package com.imyeyu.spring.handler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
*
* @author 夜雨
* @since 2026-03-16 15:42
*/
@MappedTypes(JsonNode.class)
@MappedJdbcTypes({JdbcType.VARCHAR, JdbcType.CLOB, JdbcType.LONGVARCHAR})
public class JsonNodeTypeHandler extends BaseTypeHandler<JsonNode> {
private static final ObjectMapper MAPPER = new ObjectMapper();
@Override
public void setNonNullParameter(PreparedStatement ps, int i, JsonNode parameter, JdbcType jdbcType) throws SQLException {
try {
ps.setString(i, MAPPER.writeValueAsString(parameter));
} catch (JsonProcessingException e) {
throw new SQLException("Failed to serialize JsonNode to JSON", e);
}
}
@Override
public JsonNode getNullableResult(ResultSet rs, String columnName) throws SQLException {
return parseJson(rs.getString(columnName));
}
@Override
public JsonNode getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return parseJson(rs.getString(columnIndex));
}
@Override
public JsonNode getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return parseJson(cs.getString(columnIndex));
}
private JsonNode parseJson(String json) throws SQLException {
if (json == null || json.isEmpty()) {
return MAPPER.createObjectNode();
}
try {
return MAPPER.readTree(json);
} catch (JsonProcessingException e) {
throw new SQLException("Failed to parse JSON to JsonNode", e);
}
}
}
@@ -1,6 +1,6 @@
package com.imyeyu.spring.service;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.entity.Deletable;
@@ -20,6 +20,12 @@ public abstract class AbstractEntityService<T, P> implements BaseService<T, P> {
/** 基本 Mapper */
protected BaseMapper<T, P> baseMapper;
/**
* 创建实体服务
*/
protected AbstractEntityService() {
}
/**
* 获取 Mapper 实例
*
@@ -32,7 +38,7 @@ public abstract class AbstractEntityService<T, P> implements BaseService<T, P> {
if (baseMapper == null) {
baseMapper = mapper();
}
ActionException.required(baseMapper, "mapper() can not be null");
TimiException.required(baseMapper, "mapper() can not be null");
}
@Override
@@ -1,6 +1,6 @@
package com.imyeyu.spring.service;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.timi.TimiException;
/**
* 可创建实体服务
@@ -15,7 +15,7 @@ public interface CreatableService<T> {
* 创建数据
*
* @param t 数据对象
* @throws ActionException 服务异常
* @throws TimiException 服务异常
*/
void create(T t);
}
@@ -1,6 +1,6 @@
package com.imyeyu.spring.service;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.timi.TimiException;
/**
* 可软删除实体服务
@@ -15,7 +15,7 @@ public interface DeletableService<P> {
* 软删除
*
* @param p 数据对象
* @throws ActionException 服务异常
* @throws TimiException 服务异常
*/
void delete(P p);
}
@@ -1,6 +1,6 @@
package com.imyeyu.spring.service;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.timi.TimiException;
/**
* 可销毁(物理删除)实体服务
@@ -15,7 +15,7 @@ public interface DestroyableService<P> {
* 销毁(物理删除)
*
* @param p 数据对象
* @throws ActionException 服务异常
* @throws TimiException 服务异常
*/
void destroy(P p);
}
@@ -1,6 +1,6 @@
package com.imyeyu.spring.service;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.timi.TimiException;
/**
* 可更新实体服务
@@ -15,7 +15,7 @@ public interface UpdatableService<T> {
* 修改数据
*
* @param t 数据对象
* @throws ActionException 服务异常
* @throws TimiException 服务异常
*/
void update(T t);
}
@@ -1,8 +1,8 @@
package com.imyeyu.spring.util;
import com.imyeyu.java.TimiJava;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import com.imyeyu.java.TimiJava;
import java.lang.annotation.Annotation;
@@ -16,6 +16,12 @@ import java.lang.annotation.Annotation;
*/
public abstract class AbstractValidator<A extends Annotation, T> implements ConstraintValidator<A, T> {
/**
* 创建校验器
*/
protected AbstractValidator() {
}
/**
* 验证处理器,入参验证数据,返回错误消息语言映射,返回 null 时表示通过验证
*
@@ -2,8 +2,8 @@ package com.imyeyu.spring.util;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.CallbackArgReturn;
import com.imyeyu.java.bean.ResultCode;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.java.ref.Ref;
import com.imyeyu.spring.annotation.table.AutoUUID;
import com.imyeyu.spring.annotation.table.Column;
@@ -21,7 +21,6 @@ import com.imyeyu.spring.entity.Updatable;
import com.imyeyu.spring.mapper.BaseMapper;
import com.imyeyu.utils.Text;
import com.imyeyu.utils.Time;
import lombok.Getter;
import org.apache.ibatis.builder.annotation.ProviderContext;
import java.lang.reflect.Field;
@@ -31,7 +30,6 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
@@ -82,21 +80,6 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildSelectByPageSQL(EntityMeta meta, String tableName, Page<?> page, String offset, String limit) {
return buildSelectByPageSQL(meta, tableName, page, offset, limit, "");
}
/**
* 构建分页查询 SQL
*
* @param meta 实体元数据
* @param tableName 表名
* @param page 分页参数
* @param offset 偏移量占位符
* @param limit 限制数量占位符
* @param pageParameterPath Page 参数路径前缀
* @return SQL
*/
protected String buildSelectByPageSQL(EntityMeta meta, String tableName, Page<?> page, String offset, String limit, String pageParameterPath) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT %s FROM `%s` WHERE 1 = 1".formatted(meta.selectPageClause, tableName));
@@ -104,11 +87,7 @@ public abstract class BaseSQLProvider {
appendSoftDeleteCondition(sql, meta);
// 添加 Page 查询条件
if (pageParameterPath.isEmpty()) {
appendPageConditions(sql, page);
} else {
appendPageConditions(sql, page, pageParameterPath);
}
appendPageConditions(sql, page);
// 添加排序
appendOrderBy(sql, meta, page);
@@ -127,19 +106,6 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildCountByPageSQL(EntityMeta meta, String tableName, Page<?> page) {
return buildCountByPageSQL(meta, tableName, page, "");
}
/**
* 构建分页统计 SQL
*
* @param meta 实体元数据
* @param tableName 表名
* @param page 分页参数
* @param pageParameterPath Page 参数路径前缀
* @return SQL
*/
protected String buildCountByPageSQL(EntityMeta meta, String tableName, Page<?> page, String pageParameterPath) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT COUNT(*) FROM `%s` WHERE 1 = 1".formatted(tableName));
@@ -147,11 +113,7 @@ public abstract class BaseSQLProvider {
appendSoftDeleteCondition(sql, meta);
// 添加 Page 查询条件
if (pageParameterPath.isEmpty()) {
appendPageConditions(sql, page);
} else {
appendPageConditions(sql, page, pageParameterPath);
}
appendPageConditions(sql, page);
return sql.toString();
}
@@ -175,82 +137,30 @@ public abstract class BaseSQLProvider {
* @param page 分页参数
*/
protected void appendPageConditions(StringBuilder sql, Page<?> page) {
appendPageConditions(sql, page, "");
}
/**
* 添加 Page 查询条件
*
* @param sql SQL 构建器
* @param page 分页参数
* @param pageParameterPath Page 参数路径前缀
*/
protected void appendPageConditions(StringBuilder sql, Page<?> page, String pageParameterPath) {
// 精准查询
appendPageExampleConditions(
sql,
page.getEqualsExample(),
page.getEqualsLogic(),
false,
pageParameterPath
);
if (TimiJava.isNotEmpty(page.getEqualsExample())) {
Object obj = page.getEqualsExample();
EntityMeta metaExample = getEntityMeta(obj.getClass());
String conditionClause = metaExample.fieldColumnList.stream()
.filter(fc -> fc.isNotEmpty(obj))
.map(fc -> "`%s` = '%s'".formatted(fc.columnName, fc.getAsString(obj)))
.collect(Collectors.joining(" %s ".formatted(page.getEqualsLogic())));
if (TimiJava.isNotEmpty(conditionClause)) {
sql.append(" AND ").append(conditionClause);
}
}
// 模糊查询
appendPageExampleConditions(
sql,
page.getLikesExample(),
page.getLikesLogic(),
true,
pageParameterPath
);
}
/**
* 添加一组 Page 示例条件
*
* @param sql SQL 构建器
* @param example 示例对象
* @param logic 条件连接逻辑
* @param likes 是否使用模糊匹配
* @param pageParameterPath Page 参数路径前缀
*/
private void appendPageExampleConditions(StringBuilder sql, Object example, Logic logic, boolean likes, String pageParameterPath) {
if (TimiJava.isEmpty(example)) {
return;
if (TimiJava.isNotEmpty(page.getLikesExample())) {
Object obj = page.getLikesExample();
EntityMeta metaExample = getEntityMeta(obj.getClass());
String conditionClause = metaExample.fieldColumnList.stream()
.filter(fc -> fc.isNotEmpty(obj))
.map(fc -> "`%s` LIKE CONCAT('%%', '%s', '%%')".formatted(fc.columnName, fc.getAsString(obj)))
.collect(Collectors.joining(" %s ".formatted(page.getLikesLogic())));
if (TimiJava.isNotEmpty(conditionClause)) {
sql.append(" AND (").append(conditionClause).append(')');
}
}
EntityMeta metaExample = getEntityMeta(example.getClass());
String parameterPrefix = "%s%s.".formatted(pageParameterPath, likes ? "likesExample" : "equalsExample");
String conditionClause = metaExample.fieldColumnList.stream()
.map(fc -> buildPageCondition(fc, example, likes, parameterPrefix))
.filter(Objects::nonNull)
.collect(Collectors.joining(" %s ".formatted(logic == null ? Logic.AND : logic)));
if (TimiJava.isNotEmpty(conditionClause)) {
sql.append(" AND (").append(conditionClause).append(')');
}
}
/**
* 构建单个 Page 示例条件
*
* @param fieldColumn 字段元数据
* @param example 示例对象
* @param likes 是否使用模糊匹配
* @param parameterPrefix 参数路径前缀
* @return 条件子句;字段值为空时返回 null
*/
private String buildPageCondition(FieldColumn fieldColumn, Object example, boolean likes, String parameterPrefix) {
Object value = fieldColumn.getValue(example);
if (TimiJava.isEmpty(value)) {
return null;
}
if (value instanceof Boolean booleanValue) {
return "`%s` IS %s".formatted(fieldColumn.columnName, booleanValue ? "TRUE" : "FALSE");
}
String parameter = "#{%s%s}".formatted(parameterPrefix, fieldColumn.fieldName);
if (likes) {
return "`%s` LIKE CONCAT('%%', %s, '%%')".formatted(fieldColumn.columnName, parameter);
}
return "`%s` = %s".formatted(fieldColumn.columnName, parameter);
}
/**
@@ -320,7 +230,7 @@ public abstract class BaseSQLProvider {
Ref.setFieldValue(entity, fc.field, uuid);
}
} catch (IllegalAccessException e) {
throw new ActionException(ResultCode.ERROR, "auto set field:%s value error".formatted(fc.fieldName));
throw new TimiException(TimiCode.ERROR).msgKey("auto set field:%s value error".formatted(fc.fieldName));
}
if (entity instanceof Creatable creatableEntity && creatableEntity.getCreatedAt() == null) {
creatableEntity.setCreatedAt(Time.now());
@@ -339,7 +249,7 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildSelectByIdSQL(EntityMeta meta, String tableName, String idParam) {
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
StringBuilder sql = new StringBuilder();
sql.append("SELECT %s FROM `%s` WHERE `%s` = #{%s}".formatted(
@@ -388,8 +298,8 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildUpdateSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix) {
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
ActionException.required(meta.canUpdate, "not allow update for %s".formatted(meta.entityClass));
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
TimiException.required(meta.canUpdate, "not allow update for %s".formatted(meta.entityClass));
if (entity instanceof Updatable updatable) {
updatable.setUpdatedAt(Time.now());
@@ -417,8 +327,8 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildUpdateSelectiveSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix) {
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
ActionException.required(meta.canUpdate, "not allow update for %s".formatted(meta.entityClass));
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
TimiException.required(meta.canUpdate, "not allow update for %s".formatted(meta.entityClass));
if (entity instanceof Updatable updatable) {
updatable.setUpdatedAt(Time.now());
@@ -446,8 +356,8 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildDeleteSQL(EntityMeta meta, String tableName, String idParam) {
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
ActionException.requiredTrue(meta.canDelete, "not allow soft delete for %s".formatted(meta.entityClass));
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
TimiException.requiredTrue(meta.canDelete, "not allow soft delete for %s".formatted(meta.entityClass));
return "UPDATE `%s` SET `deleted_at` = %s WHERE `%s` = #{%s}".formatted(
tableName,
@@ -468,13 +378,13 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildDeleteAllByExampleSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix, Logic logic) {
ActionException.required(meta.canDelete, "not allow delete for %s".formatted(meta.entityClass));
TimiException.required(meta.canDelete, "not allow delete for %s".formatted(meta.entityClass));
FieldColumn deleteColumn = meta.getFieldColumnList().stream()
.filter(fc -> fc.isDeleteColumn)
.findFirst()
.orElse(null);
ActionException.required(deleteColumn, "unknown delete column, use com.imyeyu.spring.annotation.table.DeleteColumn annotation on field");
TimiException.required(deleteColumn, "unknown delete column, use com.imyeyu.spring.annotation.table.DeleteColumn annotation on field");
assert deleteColumn != null;
assert deleteColumn.deleteColumnType != null;
@@ -501,8 +411,8 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildDestroySQL(EntityMeta meta, String tableName, String idParam) {
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
ActionException.requiredTrue(meta.canDestroy, "not allow destroy for %s".formatted(meta.entityClass));
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
TimiException.requiredTrue(meta.canDestroy, "not allow destroy for %s".formatted(meta.entityClass));
return "DELETE FROM `%s` WHERE `%s` = #{%s}".formatted(tableName, meta.idFieldColumn.columnName, idParam);
}
@@ -518,7 +428,7 @@ public abstract class BaseSQLProvider {
* @return SQL
*/
protected String buildDestroyAllByExampleSQL(EntityMeta meta, String tableName, Object entity, String paramPrefix, Logic logic) {
ActionException.required(meta.canDestroy, "not allow destroy for %s".formatted(meta.entityClass));
TimiException.required(meta.canDestroy, "not allow destroy for %s".formatted(meta.entityClass));
String destroyClause = meta.fieldColumnList.stream()
.filter(FieldColumn::isNotId)
.filter(fc -> fc.isNotEmpty(entity))
@@ -533,7 +443,6 @@ public abstract class BaseSQLProvider {
* @author 夜雨
* @since 2025-02-05 23:47
*/
@Getter
protected static class EntityMeta {
/** 实体类 */
@@ -583,7 +492,7 @@ public abstract class BaseSQLProvider {
this.table = Text.camelCase2underscore(entityClass.getSimpleName());
} else {
this.table = table.value();
ActionException.required(this.table, String.format("empty table annotation value for %s entity", entityClass.getName()));
TimiException.required(this.table, String.format("empty table annotation value for %s entity", entityClass.getName()));
}
List<Field> allFieldList = Ref.listAllFields(entityClass);
FieldColumn idFieldColumn = null;
@@ -595,7 +504,7 @@ public abstract class BaseSQLProvider {
}
FieldColumn fieldColumn = new FieldColumn(field);
if (fieldColumn.isId) {
ActionException.requiredNull(idFieldColumn, String.format("multi id field for %s entity", entityClass.getName()));
TimiException.requiredNull(idFieldColumn, String.format("multi id field for %s entity", entityClass.getName()));
idFieldColumn = fieldColumn;
}
fieldColumnList.add(fieldColumn);
@@ -632,6 +541,51 @@ public abstract class BaseSQLProvider {
return sb.substring(0, sb.length() - 1);
}
/**
* 获取实体类型
*
* @return 实体类型
*/
public Class<?> getEntityClass() {
return entityClass;
}
/**
* 获取表名
*
* @return 表名
*/
public String getTable() {
return table;
}
/**
* 获取查询字段映射
*
* @return 查询字段映射
*/
public String getSelectAllClause() {
return selectAllClause;
}
/**
* 获取 ID 字段映射
*
* @return ID 字段映射
*/
public FieldColumn getIdFieldColumn() {
return idFieldColumn;
}
/**
* 获取字段映射列表
*
* @return 字段映射列表
*/
public List<FieldColumn> getFieldColumnList() {
return fieldColumnList;
}
/**
* 是否可创建
*
@@ -675,7 +629,6 @@ public abstract class BaseSQLProvider {
* @author 夜雨
* @since 2025-02-07 09:54
*/
@Getter
protected static class FieldColumn {
/** 字段 */
@@ -713,7 +666,7 @@ public abstract class BaseSQLProvider {
columnName = Text.camelCase2underscore(field.getName());
} else {
columnName = column.value();
ActionException.required(columnName, "empty field:%s column annotation value for %s entity".formatted(field.getName(), field.getDeclaringClass()));
TimiException.required(columnName, "empty field:%s column annotation value for %s entity".formatted(field.getName(), field.getDeclaringClass()));
}
isId = field.isAnnotationPresent(Id.class);
isAutoUUID = field.isAnnotationPresent(AutoUUID.class);
@@ -737,7 +690,11 @@ public abstract class BaseSQLProvider {
* @return true 为 null
*/
public boolean isNull(Object entity) {
return getValue(entity) == null;
try {
return Ref.getFieldValue(entity, field, Object.class) == null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
/**
@@ -757,7 +714,11 @@ public abstract class BaseSQLProvider {
* @return true 为空
*/
public boolean isEmpty(Object entity) {
return TimiJava.isEmpty(getValue(entity));
try {
return TimiJava.isEmpty(Ref.getFieldValue(entity, field, Object.class));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
/**
@@ -777,23 +738,49 @@ public abstract class BaseSQLProvider {
* @return 字符串值
*/
public String getAsString(Object obj) {
return getValue(obj).toString();
}
/**
* 获取字段值
*
* @param entity 实体
* @return 字段值
*/
public Object getValue(Object entity) {
try {
return Ref.getFieldValue(entity, field, Object.class);
return field.get(obj).toString();
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
/**
* 获取字段
*
* @return 字段
*/
public Field getField() {
return field;
}
/**
* 获取字段名
*
* @return 字段名
*/
public String getFieldName() {
return fieldName;
}
/**
* 获取列名
*
* @return 列名
*/
public String getColumnName() {
return columnName;
}
/**
* 是否为 ID 字段
*
* @return true 为 ID 字段
*/
public boolean isId() {
return isId;
}
/**
* 是否非 ID 字段
*
@@ -802,5 +789,23 @@ public abstract class BaseSQLProvider {
public boolean isNotId() {
return !isId();
}
/**
* 是否自动 UUID
*
* @return true 为自动 UUID
*/
public boolean isAutoUUID() {
return isAutoUUID;
}
/**
* 是否自动大写 UUID
*
* @return true 为自动大写 UUID
*/
public boolean isAutoUpperUUID() {
return isAutoUpperUUID;
}
}
}
@@ -25,7 +25,7 @@ public class DynamicTableSQLProvider extends BaseSQLProvider {
*/
public String selectByPage(ProviderContext context, @Param("tableName") String tableName, @Param("page") Page<?> page) {
EntityMeta meta = getEntityMeta(context);
return buildSelectByPageSQL(meta, tableName, page, "#{page.offset}", "#{page.limit}", "page.");
return buildSelectByPageSQL(meta, tableName, page, "#{page.offset}", "#{page.limit}");
}
/**
@@ -38,7 +38,7 @@ public class DynamicTableSQLProvider extends BaseSQLProvider {
*/
public String countByPage(ProviderContext context, @Param("tableName") String tableName, @Param("page") Page<?> page) {
EntityMeta meta = getEntityMeta(context);
return buildCountByPageSQL(meta, tableName, page, "page.");
return buildCountByPageSQL(meta, tableName, page);
}
/**
@@ -1,20 +1,13 @@
package com.imyeyu.spring.util;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.ActionError;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.Response;
import com.imyeyu.java.bean.ResultCode;
import com.imyeyu.lang.MultilingualResolver;
import com.imyeyu.spring.TimiSpring;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.java.bean.timi.TimiResponse;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindException;
@@ -33,16 +26,12 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
private final ObjectProvider<MultilingualResolver> multilingualResolverProvider;
private static final String DEV_LANG_CONFIG = "dev.lang";
/**
* 创建全局异常处理器
*
* @param multilingualResolverProvider 消息解析器提供器
*/
public GlobalExceptionHandler(ObjectProvider<MultilingualResolver> multilingualResolverProvider) {
this.multilingualResolverProvider = multilingualResolverProvider;
public GlobalExceptionHandler() {
}
@Value("${spring.profiles.active}")
@@ -54,17 +43,13 @@ public class GlobalExceptionHandler {
* @param e 异常
* @return 异常返回
*/
@IgnoreGlobalReturn
@ExceptionHandler(HttpMessageConversionException.class)
public Object conversionException(HttpMessageConversionException e) {
public TimiResponse<?> conversionException(HttpMessageConversionException e) {
log.warn(e.getMessage());
if (env.contains("dev") || log.isDebugEnabled()) {
log.error("conversion error", e);
}
if (ignoreCommittedBinaryResponse()) {
return null;
}
return fail(ResultCode.ARG_BAD, "invalid.body");
return new TimiResponse<>(TimiCode.ARG_BAD).msgKey("invalid.body");
}
/**
@@ -73,17 +58,13 @@ public class GlobalExceptionHandler {
* @param e 异常
* @return 异常返回
*/
@IgnoreGlobalReturn
@ExceptionHandler(ServletException.class)
public Object headerException(ServletException e) {
public TimiResponse<?> headerException(ServletException e) {
log.warn(e.getMessage());
if (env.contains("dev") || log.isDebugEnabled()) {
log.error("header error", e);
}
if (ignoreCommittedBinaryResponse()) {
return null;
}
return fail(ResultCode.REQUEST_BAD, "invalid.request");
return new TimiResponse<>(TimiCode.REQUEST_BAD).msgKey("invalid.request");
}
/**
@@ -92,20 +73,19 @@ public class GlobalExceptionHandler {
* @param e 异常
* @return 异常返回
*/
@IgnoreGlobalReturn
@ExceptionHandler({BindException.class, ValidationException.class, MethodArgumentNotValidException.class, TypeMismatchException.class})
public Response<?> paramsException(Exception e) {
public TimiResponse<?> paramsException(Exception e) {
if (e instanceof MethodArgumentNotValidException subE) {
log.warn("request error", e);
FieldError error = subE.getBindingResult().getFieldError();
if (error != null) {
return fail(ResultCode.ARG_BAD, "[%s] %s".formatted(error.getField(), error.getDefaultMessage()));
return new TimiResponse<>(TimiCode.ARG_BAD, "[%s] %s".formatted(error.getField(), error.getDefaultMessage()));
}
}
if (env.startsWith("dev") || log.isDebugEnabled()) {
log.error("request error", e);
}
return fail(ResultCode.REQUEST_BAD, "invalid.arg");
return new TimiResponse<>(TimiCode.REQUEST_BAD).msgKey("invalid.arg");
}
/**
@@ -114,112 +94,17 @@ public class GlobalExceptionHandler {
* @param e 异常
* @return 异常返回
*/
@IgnoreGlobalReturn
@ExceptionHandler(Throwable.class)
public Object error(Throwable e) {
if (e instanceof ActionException timiE) {
public TimiResponse<?> error(Throwable e) {
if (e instanceof TimiException timiE) {
if (!env.startsWith("prod") || log.isDebugEnabled()) {
log.error(timiE.getMessage(), e);
}
if (ignoreCommittedBinaryResponse()) {
return null;
}
return fail(timiE);
}
if (e instanceof ActionError actionE) {
log.error(actionE.getMessage(), e);
if (ignoreCommittedBinaryResponse()) {
return null;
}
return fail(actionE.getCode(), actionE.getMessageCode(), actionE.getMessageArgs());
// 一般异常
return timiE.toResponse();
}
// 致命异常
log.error("fatal error", e);
if (ignoreCommittedBinaryResponse()) {
return null;
}
return fail(ResultCode.ERROR, "service.error");
}
/**
* 创建失败响应
*
* @param e 异常
* @return 响应
*/
private Response<?> fail(ActionException e) {
return fail(e.getCode(), e.getMessageCode(), e.getMessageArgs());
}
/**
* 创建失败响应
*
* @param code 代码
* @param messageCode 消息代码
* @return 响应
*/
private Response<?> fail(ResultCode code, String messageCode) {
return fail(code, messageCode, null);
}
/**
* 创建失败响应
*
* @param code 代码
* @param messageCode 消息代码
* @param messageArgs 消息插值参数
* @return 响应
*/
private Response<?> fail(ResultCode code, String messageCode, java.util.Map<String, Object> messageArgs) {
Response<?> result = new Response<>(code).messageCode(messageCode, messageArgs);
result.setMessage(resolveMessage(code, messageCode, messageArgs));
return result;
}
/**
* 解析消息
*
* @param code 代码
* @param messageCode 消息代码
* @param messageArgs 消息插值参数
* @return 消息
*/
private String resolveMessage(ResultCode code, String messageCode, java.util.Map<String, Object> messageArgs) {
if (TimiJava.isEmpty(messageCode)) {
return code.toString();
}
try {
MultilingualResolver messageResolver = multilingualResolverProvider.getIfAvailable();
if (messageResolver == null) {
return messageCode;
}
String message = messageResolver.map(TimiSpring.getLanguage()).message(messageCode, messageArgs);
return TimiJava.isEmpty(message) ? messageCode : message;
} catch (Exception e) {
log.error("message resolve error", e);
return messageCode;
}
}
/**
* 已进入二进制响应写出阶段时,不再尝试输出统一 JSON 包装,
* 否则只会制造二次异常并覆盖原始状态码。
*
* @return `true` 表示当前响应应跳过异常包装
*/
private boolean ignoreCommittedBinaryResponse() {
HttpServletResponse response = TimiSpring.getResponse();
if (response == null) {
return false;
}
if (response.isCommitted()) {
return true;
}
String contentType = response.getContentType();
if (contentType == null || contentType.isBlank()) {
return false;
}
String lowerContentType = contentType.toLowerCase();
return !lowerContentType.contains("json") && !lowerContentType.startsWith("text/");
return new TimiResponse<>(TimiCode.ERROR).msgKey("service.error");
}
}
@@ -1,9 +1,10 @@
package com.imyeyu.spring.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.java.bean.Response;
import com.imyeyu.java.bean.ResultCode;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.CallbackArgReturn;
import com.imyeyu.java.bean.LanguageMsgMapping;
import com.imyeyu.java.bean.timi.TimiCode;
import com.imyeyu.java.bean.timi.TimiResponse;
import com.imyeyu.spring.TimiSpring;
import com.imyeyu.spring.annotation.AOPLogInterceptor;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
@@ -12,7 +13,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
@@ -22,7 +22,7 @@ import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.util.Objects;
/**
* 全局返回处理器,包装 Response
* 全局返回处理器,包装 TimiResponse
*
* @author 夜雨
* @version 2023-04-30 00:59
@@ -31,15 +31,14 @@ import java.util.Objects;
public class GlobalReturnHandler implements ResponseBodyAdvice<Object> {
private static final Logger log = LoggerFactory.getLogger(GlobalReturnHandler.class);
private final ObjectMapper objectMapper;
/** 多语言头处理回调 */
private CallbackArgReturn<LanguageMsgMapping<?>, String> multilingualHeader;
/**
* 创建全局返回处理器
*
* @param objectMapper JSON 对象映射器
*/
public GlobalReturnHandler(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
public GlobalReturnHandler() {
}
@Override
@@ -54,25 +53,46 @@ public class GlobalReturnHandler implements ResponseBodyAdvice<Object> {
@NonNull MediaType selectedContentType,
@NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
@NonNull ServerHttpRequest request,
@NonNull ServerHttpResponse response
) {
Response<?> result;
if (body instanceof Response<?> Response) {
result = Response;
@NonNull ServerHttpResponse response)
{
TimiResponse<?> result;
if (body instanceof TimiResponse<?> timiResponse) {
// 可能已被全局异常包装
result = timiResponse;
} else {
result = new Response<>(ResultCode.SUCCESS, body);
result = new TimiResponse<>(TimiCode.SUCCESS, body);
}
try {
if (multilingualHeader != null && TimiJava.isNotEmpty(result.getMsgKey())) {
result.setMsg(multilingualHeader.handler(result));
} else if (TimiJava.isEmpty(result.getMsg())) {
result.setMsg(TimiCode.fromCode(result.getCode()).toString());
}
} catch (Exception e) {
log.error("multilingual response error", e);
result.setMsg(TimiCode.fromCode(result.getCode()).toString());
}
if (30000 < result.getCode()) {
log.warn("ID: {} Response -> Exception.{}.{}", TimiSpring.getSessionAttr(AOPLogInterceptor.REQUEST_ID), result.getCode(), result.getMessage());
}
if (StringHttpMessageConverter.class.isAssignableFrom(selectedConverterType)) {
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
try {
return objectMapper.writeValueAsString(result);
} catch (JsonProcessingException e) {
throw new IllegalStateException("统一响应序列化失败", e);
}
log.warn("ID: {} Response -> Exception.{}.{}", TimiSpring.getSessionAttr(AOPLogInterceptor.REQUEST_ID), result.getCode(), result.getMsg());
}
return result;
}
/**
* 获取多语言头处理回调
*
* @return 处理回调
*/
public CallbackArgReturn<LanguageMsgMapping<?>, String> getMultilingualHeader() {
return multilingualHeader;
}
/**
* 设置多语言头处理回调
*
* @param multilingualHeader 处理回调
*/
public void setMultilingualHeader(CallbackArgReturn<LanguageMsgMapping<?>, String> multilingualHeader) {
this.multilingualHeader = multilingualHeader;
}
}
@@ -1,364 +0,0 @@
package com.imyeyu.spring.util;
import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.CallbackArgReturn;
import com.imyeyu.lang.bean.Language;
import com.imyeyu.lang.bean.MultilingualValue;
import com.imyeyu.spring.TimiSpring;
import com.imyeyu.spring.annotation.MultilingualField;
import com.imyeyu.utils.StringInterpolator;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.file.Path;
import java.time.temporal.TemporalAccessor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* 统一回填响应对象中的多语言字段
*
* @author 夜雨
* @since 2026-07-17 00:00
*/
@Slf4j
public class MultilingualFieldBinder {
private static final StringInterpolator INTERPOLATOR = new StringInterpolator(StringInterpolator.SIMPLE_OBJ);
private static final Map<Class<?>, List<Field>> TRAVERSE_CACHE = new ConcurrentHashMap<>();
private static final Map<Class<?>, List<BindingField>> BINDING_CACHE = new ConcurrentHashMap<>();
private final CallbackArgReturn<Collection<String>, ? extends Collection<? extends MultilingualValue>> callback;
/**
* 创建多语言字段回填器
*
* @param callback 根据多语言 ID 查询多语言值
*/
public MultilingualFieldBinder(CallbackArgReturn<Collection<String>, ? extends Collection<? extends MultilingualValue>> callback) {
this.callback = callback;
}
/**
* 根据当前请求语言回填对象中的多语言字段
*
* @param body 响应对象
*/
public void bind(Object body) {
if (body == null) {
return;
}
LinkedHashSet<String> langIdSet = new LinkedHashSet<>();
// 第一遍只收集多语言 ID,避免递归回填时重复查询
collectLangId(body, new IdentityHashMap<>(), langIdSet);
if (langIdSet.isEmpty()) {
return;
}
Map<String, MultilingualValue> multilingualMap = new LinkedHashMap<>();
for (MultilingualValue item : callback.handler(langIdSet)) {
multilingualMap.put(item.getId(), item);
}
// 第二遍执行字段回填,模板替换也在这一遍统一完成
fillValue(body, new IdentityHashMap<>(), multilingualMap, TimiSpring.getLanguage());
}
/**
* 递归扫描响应对象,提取所有待翻译字段依赖的多语言 ID
*
* @param current 当前对象
* @param visited 已访问对象,避免循环引用死递归
* @param langIdSet 收集到的多语言 ID
*/
private void collectLangId(Object current, IdentityHashMap<Object, Boolean> visited, LinkedHashSet<String> langIdSet) {
switch (current) {
case null -> {
return;
}
case Collection<?> collection -> {
if (visited.put(current, Boolean.TRUE) != null) {
return;
}
for (Object item : collection) {
collectLangId(item, visited, langIdSet);
}
return;
}
case Map<?, ?> map -> {
if (visited.put(current, Boolean.TRUE) != null) {
return;
}
for (Object item : map.values()) {
collectLangId(item, visited, langIdSet);
}
return;
}
default -> {
}
}
if (current.getClass().isArray()) {
if (visited.put(current, Boolean.TRUE) != null) {
return;
}
int length = Array.getLength(current);
for (int i = 0; i < length; i++) {
collectLangId(Array.get(current, i), visited, langIdSet);
}
return;
}
if (isSimpleValueType(current.getClass())) {
return;
}
if (visited.put(current, Boolean.TRUE) != null) {
return;
}
for (BindingField field : getBindingFields(current.getClass())) {
String langId = getStringValue(field.langIdField(), current);
if (TimiJava.isNotEmpty(langId)) {
langIdSet.add(langId);
}
}
for (Field field : getTraverseFields(current.getClass())) {
collectLangId(getFieldValue(field, current), visited, langIdSet);
}
}
/**
* 递归回填响应对象中的多语言展示字段
*
* @param current 当前对象
* @param visited 已访问对象,避免循环引用死递归
* @param multilingualMap 本次响应涉及的多语言缓存
* @param language 当前请求语言
*/
private void fillValue(Object current, IdentityHashMap<Object, Boolean> visited, Map<String, MultilingualValue> multilingualMap, Language.Enum language) {
if (current == null) {
return;
}
if (current instanceof Collection<?> collection) {
if (visited.put(current, Boolean.TRUE) != null) {
return;
}
for (Object item : collection) {
fillValue(item, visited, multilingualMap, language);
}
return;
}
if (current instanceof Map<?, ?> map) {
if (visited.put(current, Boolean.TRUE) != null) {
return;
}
for (Object item : map.values()) {
fillValue(item, visited, multilingualMap, language);
}
return;
}
if (current.getClass().isArray()) {
if (visited.put(current, Boolean.TRUE) != null) {
return;
}
int length = Array.getLength(current);
for (int i = 0; i < length; i++) {
fillValue(Array.get(current, i), visited, multilingualMap, language);
}
return;
}
if (isSimpleValueType(current.getClass())) {
return;
}
if (visited.put(current, Boolean.TRUE) != null) {
return;
}
for (BindingField field : getBindingFields(current.getClass())) {
String langId = getStringValue(field.langIdField(), current);
if (TimiJava.isEmpty(langId)) {
continue;
}
MultilingualValue multilingual = multilingualMap.get(langId);
if (multilingual == null) {
continue;
}
String value = multilingual.getValue(language);
if (TimiJava.isEmpty(value)) {
value = multilingual.getValue(Language.Enum.zh_CN);
}
if (TimiJava.isEmpty(value)) {
continue;
}
Map<String, Object> argMap = getArgMapValue(field.argMapField(), current);
if (!argMap.isEmpty()) {
value = INTERPOLATOR.inject(value, argMap);
}
if (TimiJava.isEmpty(value)) {
continue;
}
setFieldValue(field.targetField(), current, value);
}
for (Field field : getTraverseFields(current.getClass())) {
fillValue(getFieldValue(field, current), visited, multilingualMap, language);
}
}
private List<BindingField> getBindingFields(Class<?> clazz) {
return BINDING_CACHE.computeIfAbsent(clazz, key -> {
Map<String, Field> fieldMap = new LinkedHashMap<>();
List<Field> declaredFieldList = getAllFields(key);
for (Field field : declaredFieldList) {
fieldMap.put(field.getName(), field);
}
List<BindingField> result = new ArrayList<>();
for (Field field : declaredFieldList) {
MultilingualField annotation = field.getAnnotation(MultilingualField.class);
if (annotation == null) {
continue;
}
Field langIdField = fieldMap.get(annotation.value());
if (langIdField == null) {
log.warn("MultilingualField 配置错误,类 {} 不存在字段 {}", key.getName(), annotation.value());
continue;
}
Field argMapField = null;
if (TimiJava.isNotEmpty(annotation.argMap())) {
argMapField = fieldMap.get(annotation.argMap());
if (argMapField == null) {
log.warn("MultilingualField 配置错误,类 {} 不存在字段 {}", key.getName(), annotation.argMap());
continue;
}
if (!Map.class.isAssignableFrom(argMapField.getType())) {
log.warn("MultilingualField 配置错误,类 {} 字段 {} 不是 Map", key.getName(), annotation.argMap());
continue;
}
}
result.add(new BindingField(field, langIdField, argMapField));
}
return result;
});
}
/**
* 生成需要继续向下遍历的字段列表
*
* @param clazz 目标类型
* @return 可递归字段列表
*/
private List<Field> getTraverseFields(Class<?> clazz) {
return TRAVERSE_CACHE.computeIfAbsent(clazz, key -> {
List<Field> result = new ArrayList<>();
for (Field field : getAllFields(key)) {
if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) {
continue;
}
if (field.getType().isArray() || Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())) {
field.setAccessible(true);
result.add(field);
continue;
}
if (isSimpleValueType(field.getType())) {
continue;
}
field.setAccessible(true);
result.add(field);
}
return result;
});
}
private List<Field> getAllFields(Class<?> clazz) {
List<Field> result = new ArrayList<>();
Class<?> current = clazz;
while (current != null && current != Object.class) {
for (Field field : current.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) {
continue;
}
field.setAccessible(true);
result.add(field);
}
current = current.getSuperclass();
}
return result;
}
/**
* 仅接受字符串类型的 langId 字段
*
* @param field 字段
* @param target 对象
* @return 多语言 ID
*/
private String getStringValue(Field field, Object target) {
Object value = getFieldValue(field, target);
if (value instanceof String string) {
return string;
}
return null;
}
/**
* 仅读取 Map 类型模板参数字段,未配置时返回空 Map
*
* @param field 字段
* @param target 对象
* @return 模板参数
*/
@SuppressWarnings("unchecked")
private Map<String, Object> getArgMapValue(Field field, Object target) {
if (field == null) {
return Map.of();
}
Object value = getFieldValue(field, target);
if (value instanceof Map<?, ?> map) {
return (Map<String, Object>) map;
}
return Map.of();
}
private Object getFieldValue(Field field, Object target) {
try {
return field.get(target);
} catch (IllegalAccessException e) {
throw new IllegalStateException("读取字段失败: %s#%s".formatted(target.getClass().getName(), field.getName()), e);
}
}
private void setFieldValue(Field field, Object target, Object value) {
try {
field.set(target, value);
} catch (IllegalAccessException e) {
throw new IllegalStateException("写入字段失败: %s#%s".formatted(target.getClass().getName(), field.getName()), e);
}
}
private boolean isSimpleValueType(Class<?> clazz) {
if (clazz.isPrimitive() || clazz.isEnum() || clazz.isAnnotation()) {
return true;
}
if (CharSequence.class.isAssignableFrom(clazz) || Number.class.isAssignableFrom(clazz) || Boolean.class == clazz || Character.class == clazz || UUID.class == clazz || TemporalAccessor.class.isAssignableFrom(clazz) || Class.class == clazz || JsonNode.class.isAssignableFrom(clazz) || File.class.isAssignableFrom(clazz) || Path.class.isAssignableFrom(clazz) || InputStream.class.isAssignableFrom(clazz) || OutputStream.class.isAssignableFrom(clazz) || Reader.class.isAssignableFrom(clazz) || Writer.class.isAssignableFrom(clazz)) {
return true;
}
Package currentPackage = clazz.getPackage();
if (currentPackage == null) {
return false;
}
String packageName = currentPackage.getName();
return packageName.startsWith("java.") || packageName.startsWith("javax.") || packageName.startsWith("jakarta.") || packageName.startsWith("sun.") || packageName.startsWith("com.fasterxml.jackson.");
}
private record BindingField(Field targetField, Field langIdField, Field argMapField) {
}
}
@@ -1,48 +0,0 @@
package com.imyeyu.spring.util;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
/**
* 统一处理响应中的多语言字段回填
*
* @author 夜雨
* @since 2026-07-17 00:00
*/
@Component
@RestControllerAdvice
@RequiredArgsConstructor
public class MultilingualResponseBodyAdvice implements ResponseBodyAdvice<Object> {
private final ObjectProvider<MultilingualFieldBinder> multilingualFieldBinder;
@Override
public boolean supports(@NonNull MethodParameter returnType, @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(
Object body,
@NonNull MethodParameter returnType,
@NonNull MediaType selectedContentType,
@NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
@NonNull ServerHttpRequest request,
@NonNull ServerHttpResponse response
) {
MultilingualFieldBinder binder = multilingualFieldBinder.getIfAvailable();
if (binder != null) {
binder.bind(body);
}
return body;
}
}
@@ -1,6 +1,6 @@
package com.imyeyu.spring.util;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.bean.Logic;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
@@ -25,7 +25,7 @@ public class RawSQLProvider extends SQLProvider {
@Override
public String select(ProviderContext context, Object id) {
EntityMeta meta = getEntityMeta(context);
ActionException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
TimiException.required(meta.idFieldColumn, "not found id field in %s".formatted(meta.entityClass));
return "SELECT %s FROM `%s` WHERE `%s` = #{%s}".formatted(meta.selectAllClause, meta.table, meta.idFieldColumn.columnName, id) + " LIMIT 1";
}
+35 -20
View File
@@ -1,10 +1,8 @@
package com.imyeyu.spring.util;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.ActionException;
import com.imyeyu.spring.config.AbstractRedisConfig;
import lombok.AllArgsConstructor;
import lombok.Getter;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
@@ -29,14 +27,30 @@ import java.util.function.Consumer;
* @author 夜雨
* @version 2021-11-21 09:58
*/
@AllArgsConstructor
public class Redis<K, V> {
@Getter
private RedisTemplate<K, V> redis;
private final RedisSerializer<K> serializer;
private final RedisTemplate<K, V> redis;
@Getter
private RedisSerializer<K> serializer;
/**
* 创建 Redis 操作封装
*
* @param redis RedisTemplate 实例
* @param serializer 键序列化器
*/
public Redis(RedisTemplate<K, V> redis, RedisSerializer<K> serializer) {
this.redis = redis;
this.serializer = serializer;
}
/**
* 获取 Redis 模板对象
*
* @return Redis 模板对象
*/
public RedisTemplate<?, ?> getRedis() {
return redis;
}
/**
* 加锁
@@ -87,8 +101,8 @@ public class Redis<K, V> {
* @param value 值
*/
public void setAndKeepTTL(K key, V value) {
long expire = redis.getExpire(key, TimeUnit.MILLISECONDS);
if (expire <= 0) {
Long expire = redis.getExpire(key, TimeUnit.MILLISECONDS);
if (expire == null || expire <= 0) {
// 判死
destroy(key);
} else {
@@ -196,8 +210,8 @@ public class Redis<K, V> {
public Map<K, List<V>> getAllList() {
Map<K, List<V>> r = new HashMap<>();
List<K> ks = keys("*");
for (K k : ks) {
r.put(k, getList(k));
for (int i = 0; i < ks.size(); i++) {
r.put(ks.get(i), getList(ks.get(i)));
}
return r;
}
@@ -217,13 +231,13 @@ public class Redis<K, V> {
* 获取所有值
*
* @return 所有值
* @throws ActionException 异常
* @throws TimiException 异常
*/
public List<V> values() {
List<V> r = new ArrayList<>();
List<K> ks = keys("*");
for (K k : ks) {
r.add(get(k));
List<K> keys = keys("*");
for (K key : keys) {
r.add(get(key));
}
return r;
}
@@ -236,8 +250,8 @@ public class Redis<K, V> {
public Map<K, V> map() {
Map<K, V> r = new HashMap<>();
List<K> ks = keys("*");
for (K k : ks) {
r.put(k, get(k));
for (int i = 0; i < ks.size(); i++) {
r.put(ks.get(i), get(ks.get(i)));
}
return r;
}
@@ -266,7 +280,8 @@ public class Redis<K, V> {
*/
public boolean destroy(K key) {
if (TimiJava.isNotEmpty(key) && has(key)) {
return redis.delete(key);
Boolean isSucceed = redis.delete(key);
return isSucceed != null && isSucceed;
}
return false;
}
@@ -1,12 +1,10 @@
package com.imyeyu.spring.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
@@ -85,34 +83,20 @@ public class RedisSerializers {
};
/**
* Json 序列化
* Gson 序列化
*
* @param <T> 数据类型
* @param <T> 数据类型
* @param clazz 数据类型
* @return Redis 序列化器
*/
public static <T> RedisSerializer<T> jacksonSerializer(Class<T> clazz) {
return jacksonSerializer(new ObjectMapper(), clazz);
}
/**
* Json 序列化
*
* @param <T> 数据类型
* @param mapper 序列化对象
* @param clazz 数据类型
* @return Redis 序列化器
*/
public static <T> RedisSerializer<T> jacksonSerializer(ObjectMapper mapper, Class<T> clazz) {
public static <T> RedisSerializer<T> gsonSerializer(Class<T> clazz) {
return new RedisSerializer<>() {
private static final Gson GSON = new Gson();
@Override
public byte[] serialize(T object) throws SerializationException {
try {
return mapper.writeValueAsString(object).getBytes(StandardCharsets.UTF_8);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
return GSON.toJson(object).getBytes(StandardCharsets.UTF_8);
}
@Override
@@ -120,11 +104,7 @@ public class RedisSerializers {
if (bytes == null) {
return null;
}
try {
return mapper.readValue(new String(bytes, StandardCharsets.UTF_8), clazz);
} catch (IOException e) {
throw new RuntimeException(e);
}
return GSON.fromJson(new String(bytes, StandardCharsets.UTF_8), clazz);
}
};
}
@@ -1,30 +0,0 @@
package com.imyeyu.spring.util;
/**
*
*
* @author 夜雨
* @since 2026-02-25 15:46
*/
public interface ResponseView {
/**
*
*
* @author 夜雨
* @since 2026-02-25 15:46
*/
interface Public {
}
/**
*
*
* @author 夜雨
* @since 2026-02-25 15:46
*/
interface Admin extends Public {
}
}
@@ -30,7 +30,7 @@ public class SQLProvider extends BaseSQLProvider {
*/
public String selectByPage(ProviderContext context, @Param("page") Page<?> page) {
EntityMeta meta = getEntityMeta(context);
return buildSelectByPageSQL(meta, meta.table, page, "#{offset}", "#{limit}", "");
return buildSelectByPageSQL(meta, meta.table, page, "#{offset}", "#{limit}");
}
/**
@@ -42,7 +42,7 @@ public class SQLProvider extends BaseSQLProvider {
*/
public String countByPage(ProviderContext context, @Param("page") Page<?> page) {
EntityMeta meta = getEntityMeta(context);
return buildCountByPageSQL(meta, meta.table, page, "");
return buildCountByPageSQL(meta, meta.table, page);
}
/**
@@ -25,6 +25,6 @@ public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public @org.springframework.lang.NonNull PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
return sources.getFirst();
return sources.get(0);
}
}