001package com.mybatisflex.core.datasource.processor; 002 003import com.mybatisflex.core.util.StringUtil; 004 005import java.lang.reflect.Method; 006 007/** 008 * 参数索引中取出数据源名称(针对简单类型参数快速解析读取) 009 * 010 * @author Alay 011 * @since 2024-12-07 15:43 012 */ 013public class ParamIndexDataSourceProcessor implements DataSourceProcessor { 014 private static final String NULL_STR = "null"; 015 private static final String DYNAMIC_PREFIX = "#"; 016 private static final String INDEX_FIRST = "#first"; 017 private static final String INDEX_LAST = "#last"; 018 private static final String PARAM_INDEX = "#index"; 019 020 /** 021 * 若不符合处理逻辑将返回 null 值 022 */ 023 @Override 024 public String process(String dataSourceKey, Object mapper, Method method, Object[] arguments) { 025 if (StringUtil.noText(dataSourceKey)) return null; 026 if (!dataSourceKey.startsWith(DYNAMIC_PREFIX)) return null; 027 // 无效的参数 028 if (arguments.length == 0) return null; 029 030 Integer index = null; 031 if (INDEX_FIRST.equals(dataSourceKey)) { 032 index = 0; 033 } else if (INDEX_LAST.equals(dataSourceKey)) { 034 index = arguments.length - 1; 035 } else if (dataSourceKey.startsWith(PARAM_INDEX)) { 036 index = parseIndex(dataSourceKey); 037 } 038 039 // 没有符合约定的格式输入,则会返回 null 040 if (null == index) return null; 041 // 参数输入不合法(索引参数大于参数索引数) 042 if (index >= arguments.length) return null; 043 044 // 参数中按照索引取出数值 045 String value = String.valueOf(arguments[index]); 046 if (StringUtil.noText(value) || NULL_STR.equals(value)) return null; 047 048 return value; 049 } 050 051 private static Integer parseIndex(String dsKey) { 052 // 参数索引 053 String indexStr = dsKey.substring(PARAM_INDEX.length()); 054 if (indexStr.isEmpty()) return null; 055 try { 056 return Integer.parseInt(indexStr); 057 } catch (NumberFormatException ex) { 058 return null; 059 } 060 } 061 062}