如何编写仅触发于Impex的ProductModel验证拦截器代码?
解决仅在Impex创建ProductModel时触发验证的问题
嘿,我明白你的问题了——你想让这个验证逻辑只在通过Impex创建新产品时生效,而通过BackOffice创建时跳过,对吧?因为BackOffice里没有manufacturerName和manufacturerProductId这两个字段,导致一创建就触发报错,确实挺头疼的。
问题根源
你当前的拦截器会对所有创建ProductModel的场景触发验证,不管是Impex导入还是BackOffice操作。我们需要给验证逻辑加一个“开关”,只在Impex导入的上下文里才执行。
解决方案:区分Impex与BackOffice的触发场景
Hybris在执行Impex导入时,会在会话中设置一个专门的属性impexImportSession,我们可以通过这个属性来判断当前是否是Impex导入流程。修改你的拦截器代码,添加这个判断条件即可。
另外还要注意:在调用enumerationService.getEnumerationName()之前,先检查product.getManufacturerName()是否为空,避免因为Null值抛错。
修改后的代码
@Override public void onValidate(final Object o, final InterceptorContext ctx) throws InterceptorException { if (o instanceof ProductModel) { final ProductModel product = (ProductModel) o; // 判断是否是Impex导入会话,并且是新创建的产品 final Boolean isImpexSession = (Boolean) ctx.getSession().getAttribute("impexImportSession"); if (ctx.isNew(product) && Boolean.TRUE.equals(isImpexSession)) { // 先检查manufacturerName是否不为null,避免后续调用报错 if (product.getManufacturerName() == null) { throw new InterceptorException("ManufacturerName cannot be null when importing via Impex!"); } final String manufacturerName = enumerationService.getEnumerationName(product.getManufacturerName()); final String code = product.getCode().toString(); final String manufacturerProductId = product.getManufacturerProductId(); final int a = productLookupService.getProduct(code, manufacturerName, manufacturerProductId); switch (a) { case 1: throw new InterceptorException("Product already in ProductLookup"); case 2: throw new InterceptorException( "There are more than one product with the same " + code + " number in ProductLookup !"); default: // 验证通过,无需操作 } } } }
关键说明
- Impex会话判断:
ctx.getSession().getAttribute("impexImportSession")会返回一个Boolean值,只有在Impex导入时才为true,BackOffice操作时这个属性要么不存在要么为false。 - Null值防护:新增的
product.getManufacturerName() == null检查,确保Impex导入时这个字段不会缺失,同时避免调用enumerationService时抛错。
这样修改后,BackOffice创建产品时会直接跳过验证逻辑,不会再因为字段缺失报错;而Impex导入新产品时,会正常执行你的验证规则。
内容的提问来源于stack exchange,提问作者radu
相关产品推荐
相关产品推荐

