74

I have a custom setter in my Lombok-based POJO:

@Data
@Builder
public class User {
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    private String password = null;

    public void setPassword(String password) {
        Assert.notNull(password);
        this.password = ENCODER.encode(password);
    }

but when I use the Lombok generated builder:

User user = User.builder()
    .password(password)
    .build();

my custom setter is not invoked, and so the password is not encoded. This makes me sad.

My custom setter is, of course, invoked when I use it directly:

public void changePassword(String password, User user) {
    user.setPassword(password);
}

What can I do to have Lombok's builder use my custom setter?

6 Answers 6

119

Per the documentation for @Builder: Just define enough skeleton yourself. In particular, Lombok will generate a class UserBuilder, fields mirroring the User fields, and builder methods, and you can provide any or all of this yourself.

@Builder
public class User {
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    private String username;

    private String password;

    public static class UserBuilder {
        public UserBuilder password(String password) {
            this.password = ENCODER.encode(password);
            return this;
        }
    }
}
7
  • 4
    Thanks, chrylis -- but how does Person::setPassword (from Lombok's @Data) and Person.PersonBuilder::password share a DRY implementation? Feb 22, 2017 at 0:38
  • @JanNielsen You really can't--the point of Builder is to prepopulate all of the data. Frequently, in fact, it's used with an immutable class. You might consider the "constructor" approach, calling this.setPassword() from the User class and disregarding coding issues entirely in the builder. Feb 22, 2017 at 0:55
  • 1
    @JanNielsen The more I think about it, the more it seems to make sense to make the caller responsible for encoding the password. There's just too much going on in encoding it in a property setter. Among other things, you can't set the hashed password without using direct field access. Feb 22, 2017 at 3:02
  • 3
    And for people who like me are on low-caffeine and did not understand why this code does not work: do not define a "UserBuilder" class but a <NameOfTheParentClass>Builder. I read the example a bit fast and I thought this name was a standard one in Lombok to create a "user-provided builder". May 2, 2018 at 6:31
  • 2
    When using @SuperBuilder instead of @Builder I was getting a Cannot resolve symbol password error on this.password: I solved it by using the approach explained in this answer. Sep 22, 2020 at 9:01
17

I've accepted chrylis's answer but for completeness, here's are some ways to minimize customization and duplication.

Custom setter and builder with static helper

A static helper can be used to share most of the set password functionality across the custom User.UserBuilder::password method and the custom User::setPassword method:

@Data
@Builder
public class User {
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    private String password = null;

    public void setPassword(String password) {
        this.password = _encodePassword(password);
    }
    
    public static class UserBuilder {
        public UserBuilder password(String password) {
            this.password = _encodePassword(password)
            return this;
        }
    }

    private static String _encodePassword(String password) {
        Assert.notNull(password);
        return ENCODER.encode(password);
    }
}

Custom setter and constructor

A custom constructor can use User::setPassword which is invoked by the Lombok generated User.UserBuilder::build():

@Data
@Builder
public class User {
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    private String password = null;

    User(String password) {
        setPassword(password);
    }

    public void setPassword(String password) {
        Assert.notNull(password);
        this.password = ENCODER.encode(password);
    }
}

Custom setter and constructor with static helper

Or, a little more elegantly, with a custom constructor and a static helper method:

@Data
@Builder
public class User {
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    private String password = null;

    User(String password) {
        _encodePassword(password, this);
    }

    public void setPassword(String password) {
        _encodePassword(password, this);
    }

    private static _encodePassword(String password, User user) {
        Assert.notNull(password);
        user.password = ENCODER.encode(password);
    }
}
1
  • 2
    Very informative. Unfortunately the constructor of the Custom setter and constructor example needs to take as many arguments as the class's field which can become rather messy..
    – Niccolò
    Sep 27, 2018 at 13:50
10

You are using setPassword rather than the builder's set method.

Here is what worked for me:

import lombok.Builder;
import lombok.Data;

@Builder
@Data
public class User {
    private String username;
    private String password;

    public static class UserBuilder {
        private String password;
        public UserBuilder password(String password ) {
            this.password ="ENCRIYP " +  password;
            return this;
        }
    }

    public static void main(String[] args) {
        System.out.println(User.builder().username("This is my username").password("Password").build().toString());

    }
}

The result was: User(username=This is my username, password=ENCRIYP Password)

0
4

Not really an answer to the question, but an edge case that made me to spend quite some time to find the issue.
If you have Builder with custom setter on a field with Builder.Default value, the name of the field in the generated builder class is not the same as the original field. In fact you would have two fields instead of one: password$value and password$set.
Nevertheless you can use them in the custom setter in this way:

public UserBuilder password(String password) {
  this.password$value = ENCODER.encode(password);
  this.password$set = true;
  return this;
}

The tricky part is that if you use the origianl field name, Intellij IDEA doesn't warn you about that (as if everything is fine, but of course it won't compile). Already submitted a bug report to the plugin.

1
  • 1
    This saved me some headaches. Thank you very much! Dec 10, 2020 at 8:33
1

I have come across this situation at work. Below is what I've come up with. The idea is to override Lombok's protected User(User.UserBuilder b) method

@Data
@Builder
public class User {
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    private String password;
    private Integer otherField;

    protected User(final User.UserBuilder<?, ?> b) {
        setPassword(b.password);
        otherField = b.otherField;
    }

    public void setPassword(String password) {
        Assert.notNull(password);
        this.password = ENCODER.encode(password);
    }
}
0

Just want to mention the alternative to define the Builder on a custom constructor instead of defining it on the class level.

@Data
public class User {
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    private String password = null;
    private Instant timestamp = Instant.now();

    // The builder now calls this constructor when build() is called
    @Builder
    public User(String password) {
        setPassword(password);
    }

    public void setPassword(String password) {
        Assert.notNull(password);
        this.password = ENCODER.encode(password);
    }
}

It is quite similar to "Custom setter and constructor" of Jan Nielsen, but offers a bit more control.

  • Constructor and Builder are "in sync", the Builder uses the same path to construct objects
  • You don't necessarily need to add all fields to the constructor
  • Omitted fields are not accessible in the Builder (field timestamp in the example)
1
  • Best answer of this topic for me. It respect the fact that I needed a builder not based on all my class parameters (legacy code with like 20 fields...). Sep 1 at 8:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.