代码简化

This commit is contained in:
卢春梦 2025-02-27 09:06:13 +08:00
parent 7a160bc8ba
commit 81c6541968
2 changed files with 5 additions and 12 deletions

View File

@ -17,6 +17,8 @@ package org.springblade.core.tool.sensitive;
import lombok.Getter; import lombok.Getter;
import java.util.regex.Pattern;
/** /**
* 脱敏类型枚举. * 脱敏类型枚举.
* *
@ -36,10 +38,12 @@ public enum SensitiveType {
private final String desc; private final String desc;
private final String regex; private final String regex;
private final String replacement; private final String replacement;
private final Pattern pattern;
SensitiveType(String desc, String regex, String replacement) { SensitiveType(String desc, String regex, String replacement) {
this.desc = desc; this.desc = desc;
this.regex = regex; this.regex = regex;
this.replacement = replacement; this.replacement = replacement;
this.pattern = Pattern.compile(regex);
} }
} }

View File

@ -39,9 +39,6 @@ public class SensitiveUtil {
private static final String DEFAULT_REPLACEMENT = "******"; private static final String DEFAULT_REPLACEMENT = "******";
private static final String LINE_SEPARATOR = System.lineSeparator(); private static final String LINE_SEPARATOR = System.lineSeparator();
// 预编译的正则表达式
private static final Map<SensitiveType, Pattern> PATTERN_CACHE = new EnumMap<>(SensitiveType.class);
// 预编译的默认配置 // 预编译的默认配置
private static final SensitiveConfig DEFAULT_CONFIG = SensitiveConfig.builder() private static final SensitiveConfig DEFAULT_CONFIG = SensitiveConfig.builder()
.sensitiveTypes(EnumSet.of( .sensitiveTypes(EnumSet.of(
@ -58,13 +55,6 @@ public class SensitiveUtil {
.replacement(DEFAULT_REPLACEMENT) .replacement(DEFAULT_REPLACEMENT)
.build(); .build();
static {
// 预编译所有内置的正则表达式
for (SensitiveType type : SensitiveType.values()) {
PATTERN_CACHE.put(type, Pattern.compile(type.getRegex()));
}
}
/** /**
* 使用默认配置处理敏感信息 * 使用默认配置处理敏感信息
* *
@ -206,8 +196,7 @@ public class SensitiveUtil {
private static String processRegexPatterns(String content, Set<SensitiveType> types) { private static String processRegexPatterns(String content, Set<SensitiveType> types) {
String result = content; String result = content;
for (SensitiveType type : types) { for (SensitiveType type : types) {
Pattern pattern = PATTERN_CACHE.get(type); result = type.getPattern().matcher(result).replaceAll(type.getReplacement());
result = pattern.matcher(result).replaceAll(type.getReplacement());
} }
return result; return result;
} }