You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lombok注解能否生成包含父类参数的子类构造器?

问题解答

结论

确实没办法直接用Lombok的@RequiredArgsConstructor让子类自动生成包含父类依赖的构造器。@RequiredArgsConstructor只会处理当前类里的final或@NonNull字段,不会自动继承父类的构造参数。

关于@SuperBuilder的正确用法

你之前用@SuperBuilder没得到预期结果,是因为父类和子类都得加这个注解才行。它生成的是构建器模式,不是普通构造器,但能完整处理父类的字段。

修改后的代码示例:

父类

@Controller
@SuperBuilder
public class ParentController {
    protected final HttpServletRequest request;
    protected final ITestServiceCont testServiceCont;
}

子类

@RestController
@RequestMapping("test")
@SuperBuilder
public class ChildController extends ParentController {
    private final TestService testService;
}

用构建器创建实例:

ChildController controller = ChildController.builder()
        .request(request)
        .testServiceCont(testServiceCont)
        .testService(testService)
        .build();

替代方案:简化构造器写法

如果一定要用普通构造器,目前没有Lombok注解能完全替代自定义构造器。不过可以让父类保留@RequiredArgsConstructor,子类还是得手动写构造器调用父类的方法,没法完全省掉这一步:

父类

@Controller
@RequiredArgsConstructor
public class ParentController {
    protected final HttpServletRequest request;
    protected final ITestServiceCont testServiceCont;
}

子类

@RestController
@RequestMapping("test")
public class ChildController extends ParentController {
    private final TestService testService;

    public ChildController(HttpServletRequest request, ITestServiceCont testServiceCont, TestService testService) {
        super(request, testServiceCont);
        this.testService = testService;
    }
}

这里子类加@RequiredArgsConstructor没用,因为Java要求子类构造器必须显式调用父类构造器,所以还是得手动写包含父类参数的构造器。

内容的提问来源于stack exchange,提问作者Dovile Barkauskaite

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 20:17:21