10

I'm new to lombok and guice injection, I could get the general concept but I ran into some code which I don't understand and can't search due to the syntax. Following is the code, can someone help me understand this?

import com.google.inject.Inject;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;

@AllArgsConstructor(access = AccessLevel.PRIVATE, onConstructor = @__({ @Inject }))
public class SomeClass {
...
}

Thanks!

Jin
  • 131
  • 1
  • 1
  • 5

2 Answers2

11

This is going to add a constructor with all fields as parameters, with @Inject annotation and private modifier, so your code will be expanded to:

import com.google.inject.Inject;

public class SomeClass {
    
    @Inject
    private SomeClass() {
    }
}

This is assuming there are no fields in the class. If you have some fields, then they will be added to the constructor, for example:

import com.google.inject.Inject;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;

@AllArgsConstructor(access = AccessLevel.PRIVATE, onConstructor = @__({ @Inject }))
public class SomeClass {
    private String name;
}

Will become:

import com.google.inject.Inject;

public class SomeClass {
    private String name        

    @Inject
    private SomeClass(String name) {
        this.name = name;
    }
}

Please note, that this won't work in Guice anyway, as it requires a constructor that is not private, per this documentation.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
mhaligowski
  • 2,182
  • 20
  • 26
  • 4
    "Please note, that this won't work in Guice anyway, as it requires a constructor that is not private" This is only true if the constructor doesn't have the `@Inject` annotation. With the annotation, Guice will handle it fine, except AOP won't work. – Tavian Barnes Mar 23 '17 at 13:29
0

Also make sure Lombok retains any @Named annotations you have added!

Otherwise the code below for example will fail to inject:

@AllArgsConstructor(access = AccessLevel.PACKAGE, onConstructor = @__({@Inject}))
public class SomeClass {
    @Named("example")
    private String exampleString;
}

public class ExampleModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(String.class)
          .annotatedWith(Names.named("example"))
          .toInstance("Hello, world!");
    }
}

See this answer: Lombok retain fields. You want to add

lombok.copyableAnnotations += com.google.inject.name.Named

to your lombok.config file.

Arongil
  • 11
  • 2