Jelly
Jelly

Reputation: 1308

Spring: Properly use of lombok Builder

I faced with problem while using of lombok @Builder.

In SpringBoot application I create the following component:

@Getter
@Builder
@Component
@AllArgsConstructor
public class ContentDTO {
    private UUID uuid;
    private ContentAction contentAction;
    private String payload;
}

But when I run the application< I receive:

 Error creating bean with name 'contentDTO': Unsatisfied dependency expressed through constructor parameter 0

Caused by:

 No qualifying bean of type 'java.util.UUID' available: expected at least 1 bean which qualifies as autowire candidate

"Finger to the sky", I changed lombok-builder to custom builder, like this:

 @Getter
 @Component
public class ContentDTO {

  private ContentDTO() {       
  }

 // fields

  public static Builder newBuilder() {
       return new ContentDTO().new Builder();
  }

 public class Builder{
    private Builder() {
        private constructor
    }


  public ContentDTO build() {
       return ContentDTO.this;
      }     
   }
}

And problem is gone.

Its nice, but I clearly dont understand, what was problem!

Why in this case lombok-builder prevented the autowiring of beans?

And how to use lombok-builder properly in Spring ApplicationContext?

Upvotes: 0

Views: 1239

Answers (2)

eHayik
eHayik

Reputation: 3262

Well ContentDTO has the @Component annotation therefore Spring tried to pick up and register an instance of ContentDTO in order to do so It tried to create an instance using all args constructor generated by Lombock since it was the only available constructor.

It failed due to it couldn't find registered beans with the given types expected by the ContentDTO constructor.

Adding @NoArgsConstructor or a default constructor without args like you did will work, the Builder is not related.

Upvotes: 1

adil
adil

Reputation: 11

the use of the builder requires a default constructor. When you added the @AllArgsConstructor annotation the problem appears. therefore, you must also add the @NoArgsConstructor annotation. That should be the solution for your code.

Upvotes: 1

Related Questions