java - Constructor parameter injection using guice -
this different question other answered questions constructor parameter (or @ least that's think so, course may wrong). using mapbinder store bunch of implementations , pick 1 during runtime based of criteria. here code:
public interface messageservice { void send(); } public class facebookmessageservice implements messageservice { private final string name; @inject public facebookmessageservice(string name) { this.name = name; } public void send() { system.out.println("sending message via facebook service " + name); } } public class messagemodule extends abstractmodule { @override protected void configure() { mapbinder<string, messageservice> mapbinder = mapbinder.newmapbinder<.....> mapbinder.addbinding("facebook").to(facebookmessageservice.class); } } public class messageclient { @inject map<string, messageservice> map; //mapbinder being injected public void callsender() { injector injector = guice.createinjector(new messagemodule()); injector.injectmembers(this); messageservice service = map.get("facebook"); service.send(); } }
i unable figure out how facebookmessageservice
name
parameter? if use assistedinject
factory
not able figure out how inject implementation mapbinder
.
you can inject 'name' parameter.
public class facebookmessageservice implements messageservice { private final string name; @inject public facebookmessageservice(@named("facebookservicename") string name) { this.name = name; } } public class messagemodule extends abstractmodule { @override protected void configure() { // bind "facebookservicename" // think binding should exist before map binding bindconstant().annotatedwith(names.named("facebookservicename")) .to("insert argument here"); mapbinder<string, messageservice> mapbinder = mapbinder.newmapbinder<.....> mapbinder.addbinding("facebook").to(facebookmessageservice.class); } }
put debug point in facebookmessageservice constructor see whether works.
Comments
Post a Comment