WowBow
WowBow

Reputation: 7603

How to Inject implementation in Guice 4.0

I had this class as follows which works fine

@Singleton
public class EmpResource {

private EmpService empService;

@Inject
    public EmpResource(EmpService empService) {
        this.empService=empService;
    }

}

public class EmpService {

public void getName(){..}

}

Now instead of using EmpService directly, I had to create an interface and EmpService implement that interface as follows.

public interface IEmpService{
 void getName();
}

public class EmpServiceImpl implements IEmpService {
public void getName(){...}
}

So now my resource class has to use the interface but I am not sure how to reference the implementation it has to use.

@Singleton
public class EmpResource {

private IEmpService empService;

@Inject
    public EmpResource(IEmpService empService) {
        this.empService=empService;
    }

}

I've seen this and I wasn't sure where my binding should go. (This is my first project related to Guice so I am a total newbie).

This is the error that came "No implementation for com.api.EmpService was bound." which is totally understandable but not sure how to fix it. I appericiate your help.

FYI: I am using Dropwizard application.

Upvotes: 0

Views: 321

Answers (2)

Michael Meyer
Michael Meyer

Reputation: 2184

you also have to add a Provide Methode for your EmpServiceImpl class

public class MyModule  extends AbstractModule {

    @Override
    protected void configure() {
             bind(IEmpService.class).to(EmpServiceImpl.class);
    }

    @Provides
    EmpServiceImpl provideEmpServiceImpl()  {
        // create your Implementation here ... eg.
        return new EmpServiceImpl();
    } 

}

Upvotes: 0

Thomas Fritsch
Thomas Fritsch

Reputation: 10127

You would configure your module similar to this:

public class YourModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(EmpService.class).to(EmpServiceImpl.class);
        // ....
    }
}

Upvotes: 2

Related Questions