springBoot + Thymeleaf:使用 Lombok 读取值

问题描述 投票:0回答:1

我有这个豆子:

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BlogSearchDataPayload {

    String langCode;
    String blogCategory = BlogCategoryEnum.all.name();


}

控制器:

  @GetMapping({"/blogs", "/"})
    public String index(@RequestParam(name = "langCode", required = false) String langCode,
                        @RequestParam(name = "blogCategory", required = false) String blogCategory,
                        final ModelMap model) throws ExecutionException, InterruptedException {

        model.addAttribute("blogItems",
                blogItems(langCode, blogCategory, null, null));
        model.addAttribute("searchFilter", BlogSearchDataPayload.builder());

        return "blogs";
    }

和模板:

<select name="blogCategory" th:field="*{searchFilter.blogCategory}" th:id="blogCategory" onchange="updateAction()">
                    <option value="all">All</option>
                    <option value="transits">Transits</option>
                    <option value="natalchart">Natal Chart</option>
                    <option value="solarreturn">Solar Return</option>
                    <option value="synastry">Synastry</option>
                </select>

但是我有这个错误:

Caused by: org.springframework.beans.NotReadablePropertyException: Invalid property 'blogCategory' of bean class [com.mysticriver.web.payload.BlogSearchDataPayload$BlogSearchDataPayloadBuilder]: Bean property 'blogCategory' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
    at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:627)
    at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:617)
java spring spring-boot thymeleaf spring-thymeleaf
1个回答
0
投票

也许您错误地使用了构建器。建造者不应该这样使用。

简而言之,你可以这样修复:

@GetMapping({"/blogs", "/"})
public String index(@RequestParam(name = "langCode", required = false) String langCode,
                    @RequestParam(name = "blogCategory", required = false) String blogCategory,
                    final ModelMap model) throws ExecutionException, InterruptedException {

        model.addAttribute("blogItems", blogItems(langCode, blogCategory, null, null));
        model.addAttribute("searchFilter", new BlogSearchDataPayload());
        return "blogs";

}

进一步解释一下,只要你想用任意参数创建对象,你就应该使用 builder。例如,类

Cat
可能有很多字段(颜色、声音、眼睛、毛皮等),并且为其创建构造函数非常困难(由于有很多组合)。在这种情况下,类
CatBuilder
应按如下方式使用:

private getMyCat() {
    Cat cat = Cat.builder()
                 .color("Yellow")
                 .eye("Blue")
                 .build();
    return cat;
}
© www.soinside.com 2019 - 2024. All rights reserved.