0

I am using Lombok framework for boilerplate code generation, for example:

import lombok.*;


@Builder
@Value
public final class SocketConfig {

    @Builder.Default
    private int soTimeoutMilliseconds = 0;

    @Builder.Default
    private boolean soReuseAddress = false;

    @Builder.Default
    private int soLingerSeconds = -1;

    private boolean soKeepAlive;

    @Builder.Default
    private boolean tcpNoDelay = false;

} 

In order to create builder instances I used to invoke SocketConfig.builder(). But for better integration with spring beans creation I tried to create a FactoryBean. But got a compilation error due to lack of default constructor on the builder class, didn't find any documentation about it. Is it possible with Lombok? I mean to create a default constructor on the builder not on the original class. In other words, I want 2 options to create the builder instance: SocketConfig.builder() or through new SocketConfig.SocketConfigBuilder().

import org.springframework.beans.factory.FactoryBean;

public class SocketConfigFactoryBean extends SocketConfig.SocketConfigBuilder implements FactoryBean<SocketConfig> {



    @Override
    public SocketConfig getObject() throws Exception {
        return build();
    }

    @Override
    public Class<?> getObjectType() {
        return SocketConfig.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}
Maxim Kirilov
  • 2,639
  • 24
  • 49
  • Possible duplicate of [Lombok @Builder and JPA Default constructor](https://stackoverflow.com/questions/34241718/lombok-builder-and-jpa-default-constructor) – Yassin Hajaj May 14 '18 at 09:05
  • Don't extend `SocketConfig.SocketConfigBuilder` just encapsulate it. – M. Deinum May 14 '18 at 10:48
  • In this case I will need to maintain all fields names in the current class as well. – Maxim Kirilov May 14 '18 at 10:51
  • 1
    No you don't. Create a `builder` inside the factory and simply expose setters for the properties which directly set the values on the encapsulated builder. – M. Deinum May 14 '18 at 11:00

1 Answers1

1

Use the annotation NoArgsConstructor:

Generates a no-args constructor. Will generate an error message if such a constructor cannot be written due to the existence of final fields.

Read also this.

pzaenger
  • 11,381
  • 3
  • 45
  • 46
  • This will generate a constructor on the original class not on the inner builder class. – Maxim Kirilov May 14 '18 at 09:46
  • Then [this answer](https://stackoverflow.com/a/35602246/2436655) might help you. Thanks to @MaximKirilov for his comment. – pzaenger May 14 '18 at 09:49
  • It doesn't, it will generate 2 constructors on the constructed class. I want 2 options to create the builder instance: "SocketConfig.builder()" or through "new SocketConfig.SocketConfigBuilder()" – Maxim Kirilov May 14 '18 at 09:53