Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lombok and guice injection

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!

like image 288
Jin Avatar asked Mar 20 '17 17:03

Jin


People also ask

What is Guice injector?

public interface Injector. Builds the graphs of objects that make up your application. The injector tracks the dependencies for each type and uses bindings to inject them. This is the core of Guice, although you rarely interact with it directly.

Why Autowired field injection is not recommended?

The reasons why field injection is frowned upon are as follows: You cannot create immutable objects, as you can with constructor injection. Your classes have tight coupling with your DI container and cannot be used outside of it. Your classes cannot be instantiated (for example in unit tests) without reflection.

How does Guice dependency injection work?

Guice figures out how to give you an Emailer based on the type. If it's a simple object, it'll instantiate it and pass it in. If it has dependencies, it will resolve those dependencies, pass them into it's constructor, then pass the resulting object into your object.


1 Answers

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.

like image 73
mhaligowski Avatar answered Nov 13 '22 03:11

mhaligowski