0

Two methods to inject into constructor:

@Slf4j
@Component
@RequiredArgsConstructor (onConstructor = @_(@Inject))
public ClassA {
   @NonNull private ClassB b;
}

Another method is using Inject:

@Slf4j
@Component
public class ClassA {
   private final ClassB b;
   @Inject
   public ClassA(ClassB b) {
      this.b = b;
   }
}

Wondering any difference?

LookIntoEast
  • 8,048
  • 18
  • 64
  • 92

1 Answers1

1

Yes, there is a lot more code in the latter :). Lombok does some magic in the compile phase and maybe the bytecode of those two are a bit different but the result bytecode should be almost the same and the and functionality exactly same.

Out of the scope: Note that - depending on the case - it might be yet more clear to inject the field directly:

@Inject
private final ClassB b;

Difference with that would be that b would be injected only after constructor has been executed and for that then you would need to create method with @PostConstruct that does things that otherwise should have been done in the constructor.

pirho
  • 11,565
  • 12
  • 43
  • 70