如何自定义 @IdCard 注解并在验证器中访问 Spring 注入的 ID 校验服务?
解读
面试官想通过这道题同时考察三层能力:
- 对 Struts2 验证体系 的掌握,尤其是 自定义注解级验证 的完整生命周期;
- 对 Spring 与 Struts2 深度整合 的理解,能否在 非 Spring 托管对象(ValidationInterceptor 创建的验证器实例)里拿到 Spring Bean;
- 对 中国身份证号码校验规则(GB11643-1999)的落地实现是否严谨,包括 15 位转 18 位、加权因子、校验位 等细节。
这道题在国内政府、金融、运营商项目里出现频率极高,答不出“Spring 注入”这一步基本会被判定为只能写“玩具代码”。
知识点
- Struts2 验证注解扩展点:@ValidatorAnnotation 元注解、Validator 接口、AnnotationValidatorManager;
- Spring 插件 struts2-spring-plugin 的 ObjectFactory 与 autowire 策略;
- Spring Bean 注入的三种姿势:
- 验证器实现 ApplicationContextAware;
- 在 struts.xml 打开
<constant name="struts.objectFactory.spring.autoWire.alwaysRespect" value="true"/>; - 用
@Inject或 Spring 的@Component把验证器本身托管给 Spring;
- 中国身份证校验算法:前 17 位加权求和 → 模 11 → 映射校验码;
- Struts2 验证器必须是线程安全的,因为 Validator 实例会被复用。
答案
步骤一:定义注解
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@ValidatorAnnotation(type = IdCardValidator.class)
public @interface IdCard {
String message() default "身份证号码格式错误";
}
步骤二:实现验证器,并解决 Spring 注入
public class IdCardValidator implements Validator<IdCard>, ApplicationContextAware {
private static ApplicationContext ctx;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
ctx = applicationContext; // 静态保存,保证后续复用
}
@Override
public void validate(Object object, IdCard annotation, String fieldName)
throws ValidationException {
String idValue = (String) Ognl.getValue(fieldName, object);
if (idValue == null || idValue.length() == 0) return;
// 从 Spring 容器里拿真正的校验服务
IdCardCheckService service = ctx.getBean(IdCardCheckService.class);
if (!service.verify(idValue)) {
throw new ValidationException(annotation.message());
}
}
}
步骤三:把验证器托管给 Spring
<!-- spring-context.xml -->
<bean class="validator.IdCardValidator"/>
步骤四:在 struts.xml 开启 Spring 自动装配
<constant name="struts.objectFactory" value="spring"/>
<constant name="struts.objectFactory.spring.autoWire.alwaysRespect" value="true"/>
步骤五:在 Action 中直接使用
public class UserAction extends ActionSupport {
@IdCard
private String idCard;
// getter/setter
}
部署后,ValidationInterceptor 会在 params 拦截器之后 触发,IdCardValidator 由 Spring 创建并完成依赖注入,线程安全地复用,消息回显通过 fieldError 回传到前端。
拓展思考
- 如果项目采用 注解驱动零 XML,可把 IdCardValidator 标注为
@Component("idCardValidator"),并在 struts-plugin.xml 里通过 @BeanParam 方式注册,实现 100% 无 XML; - 当 并发量高 时,静态持有 ApplicationContext 可能带来 类加载器泄漏,可改为 构造函数注入 并把验证器配置为 prototype,让 Spring 每次都提供新实例;
- 若校验规则需 热更新(例如公安部接口地址变化),可把 IdCardCheckService 实现为 Spring Cloud Config 客户端,动态刷新 @ConfigurationProperties;
- 在 微服务拆分 后,身份证校验服务独立部署,可在 IdCardValidator 里通过 @FeignClient 调用,Validator 本身作为熔断入口,兼顾 Struts2 老系统 与 Spring Cloud 新架构 的平滑共存。