Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting Constructor Parameter value using Google Guice

I have a simple requirement -

This is the service where I want to inject the object of CalledService.

public class CallingService {

    private CalledService service;

    @Inject
    public CallingService(CalledService svc) {
        service = svc;
    }
}

The CalledService looks like this -

public class CalledService {

    private String variable_value;

    public CalledService(String parameter) {
        variable_value = parameter;
    }

}

And let's say in the psvm, I am writing this code for execution -

Injector injector = Guice.createInjector(new AppInjector());        
CallingService service = injector.getInstance(CallingService.class);

The issue is if CalledService had a non-parameterised constructor then it would have worked fine. But since it is a parameterised I don’t know how I can inject the parameter value.

Also, several other services might want to inject the CalledService with different parameter values. So I don't want to bind any static value to the parameter.

Can anyone suggest the simplest way this can be achieved using Google Guice? Also, I found a lot of answers in this forum but they were not exactly what I was looking for, and some solutions were overly complicated. Thanks in advance.

like image 229
Rito Avatar asked Apr 16 '26 18:04

Rito


1 Answers

In addition to the suggestion in the comment above - assisted inject You can bind instances in Guice. Please see here for details/examples

Hope this helps

like image 135
Luigi Avatar answered Apr 19 '26 11:04

Luigi