Thymeleaf 3 地图访问与点符号

Thymeleaf 3 map access with dot notation

在 spring 4.3.x 环境中将 thymeleaf 从 2.x 更新为 3.x 时,我遇到的问题是 class org.thymeleaf.context.VariablesMap 已删除。 我正在使用以下模型结构

public interface Model extends Map<String, Object>, Serializable {...}
public class BaseModel extends VariablesMap<String, Object> implements Model {...}

VariablesMap 实现了一个 OGNL MapPropertyAccessor,它允许使用点符号访问模型,无论键 alternativeLanguages 是否存在

${meta.alternativeLanguages}

现在使用 thymeleaf 3,spring 集成仅使用 SpringEL,当键 alternativeLanguages 不存在时,SpringEL MapAccessor 会抛出异常

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 28): Property or field 'alternativeLanguages' cannot be found on object of type 'd.v.BaseModel' - maybe not public?

有没有办法避免所有模板迁移到

${meta['alternativeLanguages']}

在这种情况下,您可以使用安全的空导航: ${meta?.alternativeLanguages} https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#expressions-operator-safe-navigation

这只是部分答案,因为我还没有尝试过,但我猜你必须根据(可能继承自)org.springframework.context.expression.MapAccessor 来实现你自己的 org.springframework.expression.PropertyAccessor那并没有完全按照您的意愿行事。对于 canRead 方法,您几乎总是希望 return 为真,并将 read 方法处理为 return 无论您想要什么 return如果地图中没有值。

然后我假设您需要以某种方式了解 Thymeleaf 如何创建其 SpEL 上下文以注册该自定义 PropertyAccessor,我希望这是可能的,但我没有快速查看在哪里通过.

不过,我希望这能为您指明正确的方向。