敏感词
简介
continew-starter-security-sensitivewords 是 ContiNew Starter 安全模块提供的敏感词检测模块(@since 2.9.0),基于 Hutool DFA 算法实现敏感词匹配,提供编程式检测服务与 Bean Validation 校验注解。
主要特性
- 服务化检测: 提供
SensitiveWordsService接口,编程式检测文本中的敏感词 - 校验注解: 提供
@SensitiveWords注解,与 Jakarta Validation 无缝集成 - 可插拔词库: 默认词库来自配置项,支持通过实现
SensitiveWordsConfig接口自定义词库来源
快速开始
引入依赖
xml
<dependency>
<groupId>top.continew.starter</groupId>
<artifactId>continew-starter-security-sensitivewords</artifactId>
</dependency>添加配置
配置详情请查看:top.continew.starter.security.sensitivewords.autoconfigure.SensitiveWordsProperties(@since 2.9.0)。
模块不内置词库文件,默认词库即配置项 values:
yaml
--- ### 敏感词配置
continew-starter.security:
sensitive-words:
# 敏感词列表
values:
- 敏感词一
- 敏感词二自定义词库来源
需要从数据库等外部来源加载词库时,实现 SensitiveWordsConfig 接口并注册为 Bean 即可,自动配置提供的默认实现(@ConditionalOnMissingBean)会自动让位。
编程式检测
注入 SensitiveWordsService,调用 check(String content),返回命中的敏感词列表。
java
@RequiredArgsConstructor
@Service
public class DemoService {
private final SensitiveWordsService sensitiveWordsService;
public void check(String content) {
List<String> hitWords = sensitiveWordsService.check(content);
// ...
}
}使用 @SensitiveWords 注解校验
在 String 类型的字段/参数上标注 @SensitiveWords(默认消息:内容包含敏感词汇),命中时校验消息为:内容包含敏感词汇: 命中词1,命中词2。
java
@Data
public class CommentReq {
@SensitiveWords
private String content;
}核心依赖
| 依赖 | 描述 |
|---|---|
| top.continew.starter:continew-starter-core | 核心模块 |
| cn.hutool:hutool-dfa | Hutool DFA 模块(基于 DFA 的关键词查找) |
| org.springframework.boot:spring-boot-starter-validation | Spring Boot 校验模块(Hibernate Validator) |
参考资料
- Hutool DFA 模块文档:https://hutool.cn/docs/#/dfa/概述