如何在Hybris中获取item type属性的本地化名称?
自定义ItemType字段本地化名称获取方案
有开箱即用的平台内置服务可以直接实现需求,不需要自行封装工具类:
- 核心依赖两个平台默认注入的服务即可:
TypeService、LocalizationService - 第一步调用
TypeService的getComposedTypeForCode()方法,传入你自定义的itemtype编码,拿到对应的ComposedTypeModel实例 - 第二步调用实例的
getAttributes()方法,就能拿到该itemtype下所有字段对应的AttributeDescriptorModel集合,包含继承自父类型的字段、你自行新增的字段 - 第三步调用
LocalizationService的getLocalizedString()方法,传入AttributeDescriptor的name属性和目标语言Locale,就能直接拿到对应字段的本地化名称;如果不传Locale,默认取当前会话的语言配置 - 如果你是在适配后台管理端、cockpit这类前端接口场景,直接调用更高层封装的
TypeFacade即可,它的getAttributeDescriptorsForType()方法返回的DTO里已经直接带好本地化后的字段名,不需要手动处理语言逻辑
常见踩坑提示:如果返回的名称是字段的qualifier(也就是字段编码)而不是你配置的本地化文案,先检查对应语言包下是否配置了
type.[你的itemtype编码].[字段qualifier].name=对应本地化文案的键值对,服务在找不到对应本地化配置时会用字段编码做兜底返回,不会抛异常。
最小实现代码参考:
import de.hybris.platform.core.model.type.AttributeDescriptorModel; import de.hybris.platform.core.model.type.ComposedTypeModel; import de.hybris.platform.servicelayer.localization.LocalizationService; import de.hybris.platform.servicelayer.type.TypeService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; @Service public class CustomItemTypeService { @Resource private TypeService typeService; @Resource private LocalizationService localizationService; /** * 获取指定itemtype所有字段的本地化名称 * @param itemTypeCode 自定义itemtype编码 * @param targetLocale 目标语言 * @return key为字段编码,value为对应本地化名称 */ public Map<String, String> getFieldLocalizedNames(String itemTypeCode, Locale targetLocale) { ComposedTypeModel targetType = typeService.getComposedTypeForCode(itemTypeCode); return targetType.getAttributes().stream() .collect(Collectors.toMap( AttributeDescriptorModel::getQualifier, attr -> localizationService.getLocalizedString(attr.getName(), targetLocale) )); } }
内容的提问来源于stack exchange,提问作者Rupesh Vislawath
相关产品推荐
相关产品推荐

