Thymeleaf调用枚举name()报EL1011E SpelEvaluationException异常
报错原因
SpelEvaluationException: EL1011E: Method call: Attempted to call method name() on null context object 触发的直接原因是:遍历produtos集合时,存在部分Produto实例的status属性为null,执行${produto.status.name()}时相当于在null值上调用name()方法,触发空指针。
另外你贴的模板代码里,CELULAR分类对应的div标签末尾多写了一个冗余的右尖括号>,会导致页面DOM结构异常,虽然不是本次报错的诱因,但也需要修正。
修复方法
- 模板层增加空值判断,避免直接在可能为null的属性上调用方法
调整后的模板代码如下,空值场景增加兜底展示:<main> <div class="container"> <h2 class="text-center">Produtos</h2> <div class="row"> <div class="d-flex align-items-stretch" style="flex-direction: row; flex-wrap: wrap; justify-content:center;"> <div class="col-md-4 col-xl-3 col-lg-3 col-sm-6 mx-1 my-2" th:each="produto : ${produtos}"> <!-- 非空场景走分类判断 --> <th:block th:if="${produto.status != null}"> <th:block th:switch="${produto.status.name()}"> <div th:case="'ACESSORIOS'" class="card border-dark bg-dark text-white text-center"></div> <div th:case="'CELULAR'" class="card border-primary bg-dark text-white text-center"></div> <div th:case="'COMPUTADOR'" class="card border-light bg-dark text-white text-center"></div> </th:block> </th:block> <!-- 空分类兜底 --> <div th:unless="${produto.status != null}" class="card border-secondary bg-dark text-white text-center"> 未分类商品 </div> </div> </div> </div> </div> </main> - 源头修复空值问题
- 检查数据库produto表的status字段,把值为NULL的记录补全正确的分类枚举值。
- 业务层新增/更新商品时,加参数校验,强制status字段不能为null,避免脏数据入库。
- 可选优化:枚举判断更稳妥的写法
可以直接通过类路径加载枚举类做值对比,不需要手动调用name()方法,降低空指针风险,注意替换成你自己项目里Statuscategoria的实际全类名:<th:block th:switch="${produto.status}"> <div th:case="${T(com.yourpackage.enums.Statuscategoria).ACESSORIOS}" class="card border-dark bg-dark text-white text-center"></div> <div th:case="${T(com.yourpackage.enums.Statuscategoria).CELULAR}" class="card border-primary bg-dark text-white text-center"></div> <div th:case="${T(com.yourpackage.enums.Statuscategoria).COMPUTADOR}" class="card border-light bg-dark text-white text-center"></div> </th:block>
内容的提问来源于stack exchange,提问作者Ian França
相关产品推荐
相关产品推荐

