简体   繁体   English

Lombok 中带有静态助手的自定义 setter 和构造函数

[英]Custom setter and constructor with static helper in Lombok

I want to use Custom setter and constructor with static helper in Lombok:我想在 Lombok 中使用带有静态助手的自定义设置器和构造函数:

@SuperBuilder(toBuilder = true)
public class Teacher extends User {
}


@Data
@SuperBuilder(toBuilder = true)
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(NON_NULL)
public class User implements Employee {
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    private String username;
    private String password;

    User(String username, String password) {
        System.out.println("*** test ***");

    }
}

but when I create a Teacher object it seems that the constructor is not called because I don't see the test message in the console但是当我创建一个 Teacher 对象时,似乎没有调用构造函数,因为我在控制台中没有看到测试消息

Teacher.builder()
 .username("username").password("pwd").build();

The point of the Builder pattern is almost always to return an immutable object from a builder object that is inherently mutable.构建器模式的要点几乎总是从本质上可变的构建器对象返回一个不可变对象。 The static helper you're referring to is the Builder pattern factory method used to create the User object.您所指的静态助手是用于创建 User 对象的 Builder 模式工厂方法。 You shouldn't need to create a setter for User, instead User should be not defined with @Data.您不需要为 User 创建一个 setter,而是不应该使用 @Data 定义 User。

If you need to call some method after construct of the User or Employee object just add a function to the respective class and call it after construct.如果您需要在构造 User 或 Employee 对象后调用某些方法,只需向相应的类添加一个函数并在构造后调用它。 Hiding work inside of a constructor other than initializing class members can be dangerous because you're hiding functionality and if it's a private method that functionality cannot be overridden.除了初始化类成员之外,在构造函数中隐藏工作可能很危险,因为您隐藏了功能,并且如果它是一个私有方法,则该功能不能被覆盖。

    @SuperBuilder(toBuilder = true)
    public static class Teacher extends User {

    }

    @AllArgsConstructor
    @SuperBuilder(toBuilder = true)
    public static class User implements Employee {

        private final String username;

        private final String password;
    }

    public static void main(String[] args) {
        Teacher teacher = Teacher.builder()
                .username("username").password("pwd").build();

        System.out.println(teacher.toString());
    }

    interface Employee {

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM