Hybris技术问题:如何从上下文获取枚举的名称?
在Hybris拦截器中从InterceptorContext获取枚举名称的方法
嘿,我来帮你搞定在Hybris拦截器里从InterceptorContext获取枚举名称的事儿,结合你给出的ProductModel校验代码,咱们一步步捋清楚:
核心思路
Hybris里的枚举名称通常是本地化的(不同语言显示不同名称),所以我们需要借助上下文的Locale和Hybris的国际化服务来获取正确的枚举名称,而不是直接调用枚举的toString()(那通常只是枚举的code或者默认实现,不是本地化名称)。
具体实现步骤
注入国际化服务
首先在你的拦截器类里注入CommonI18NService,这个服务是Hybris用来处理本地化枚举名称的核心工具:import de.hybris.platform.servicelayer.i18n.CommonI18NService; import org.springframework.beans.factory.annotation.Autowired; public class YourProductValidateInterceptor implements ValidateInterceptor { @Autowired private CommonI18NService commonI18NService; // 你的onValidate方法... }从InterceptorContext获取Locale
在onValidate方法里,通过InterceptorContext可以拿到当前请求上下文对应的Locale,这是获取本地化名称的关键:Locale currentLocale = ctx.getLocale();获取枚举实例并获取其本地化名称
假设你的ProductModel有一个枚举属性(比如ProductStatus类型的status字段),先拿到枚举实例,再用国际化服务获取名称,把逻辑整合到你的校验代码里:public void onValidate(final Object o, final InterceptorContext ctx) throws InterceptorException { if (o instanceof ProductModel) { final ProductModel product = (ProductModel) o; if (!ctx.isNew(product)) { // 你的原有校验逻辑 if (StringUtils.isEmpty(product.getCode())) { throw new InterceptorException("The Code must not be empty!"); } if (product.getManufacturerName() == null || StringUtils.isEmpty(product.getManufacturerName().toString())) { throw new InterceptorException("The ManufacturerName must not be empty!"); } // 新增枚举名称获取逻辑 ProductStatus productStatus = product.getStatus(); if (productStatus == null) { throw new InterceptorException("The Product Status must not be empty!"); } // 获取本地化的枚举名称 String enumDisplayName = commonI18NService.getEnumerationName(productStatus, currentLocale); if (StringUtils.isEmpty(enumDisplayName)) { throw new InterceptorException(String.format("No localized name found for ProductStatus: %s, locale: %s", productStatus.getCode(), currentLocale)); } // 你的其他校验逻辑... } } }
关键注意事项
- 枚举的本地化配置:要确保你的枚举在
items.xml里正确配置,并且对应语言的资源文件(比如messages_en.properties、messages_zh.properties)里存在枚举名称的键值对,例如:<!-- items.xml里的枚举定义 --> <enumeration type="ProductStatus"> <value code="ACTIVE" /> <value code="INACTIVE" /> </enumeration># messages_en.properties里的配置 enumeration.ProductStatus.ACTIVE=Active enumeration.ProductStatus.INACTIVE=Inactive - 如果只需要枚举Code:如果不需要本地化名称,只是要枚举的标识,直接调用
productStatus.getCode()即可,不需要用到国际化服务。 - Interceptor的Spring配置:确保你的拦截器被Spring容器管理,这样注入的
CommonI18NService才能正常生效。
内容的提问来源于stack exchange,提问作者radu
相关产品推荐
相关产品推荐

