Here's something weird. Suppose you have a module like this:
public class ParentModule extends AbstractModule {
#Override
public void configure() {
bindConstant().annotatedWith(Names.named("key")).to("key");
}
}
Then we also have something like this:
public class DependentModule extends AbstractModule {
private final String key;
#Inject public DependentModule(#Named("key") String key) { this.key = key; }
#Override
public void configure() {
// Configure bindings that make use of key...
}
}
Injector parent = Guice.createInjector(new ParentModule());
Injector child = parent.createChildInjector(parent.getInstance(DependentModule.class));
// Now just ignore parent and work with child exclusively
This seems extremely cumbersome, but possibly necessary and useful in certain situations (if the key is a more complex datatype, for instance). Regardless, is there a way to restructure this code such that ParentModule binds the key, creates the DependentModule using the key, and install the created DependentModule? That is, such that the consumer can simply use a single injector instead of having to do this two-injector trick?
It isn't possible to inject something and then install it. Injection only happens after all your configure() methods have run, by which point it's too late. But you can do this:
public class MyModule extends AbstractModule {
#Override
public void configure() {
bindConstant().annotatedWith(Names.named("key")).to("key");
}
#Provides
Dependency provideDependency(#Named("key") String key) {
// Use key here
}
}
Related
there is a configuration file that I want to bind using Guice but the problem is I get that file using my manager class and I don't have an instance of it. To make clear, I explain on code:
public class GuiceModule extends AbstractModule {
#Override
protected void configure() {
bind(ConfigManager.class).to(SimpleConfigManager.class).asEagerSingleton(); // My manager
bind(PropertiesConfiguration.class).annotatedWith(Names.named("versionConfig")).toInstance(configManager.getResourceConfig("version.properties"));
// ^ I need an instance of SimpleConfigManager here
}
}
So, how can I create/get an instance without using the "new" keyword?
You can use something called ProvidesMethod.
public class GuiceModule extends AbstractModule {
#Override
protected void configure() {
bind(ConfigManager.class).to(SimpleConfigManager.class).asEagerSingleton();
}
#Provides
#Singleton
#Named("versionConfig")
public PropertiesConfiguration providePropertiesConfiguration(ConfigManager configManager) {
return configManager.getResourceConfig("version.properties");
}
}
Heres my current setup
Class file
public class ToyAdapter {
private final ToyClient toyClient;
private final Retryer retryer;
#Inject
public APIAdapter(final ToyClient toyClient,
#Named("toyRetryer") final Retryer retryer) {
this.toyClient = toyClient;
this.retryer = retryer;
}
Guice file
I have several guice modules, but this one pertains to the above class
public class ToyModule extends AbstractModule {
#Override
protected void configure() {
bind(ToyAdapter.class).in(Singleton.class);
bind(Retryer.class).annotatedWith(Names.named("toyRetryer")).toInstance(getToyRetryer());
}
#Provides
#Singleton
public ToyClient getToyClient(...){
...
}
private Retryer getToyRetryer() {#Takes no arguments
return RetryerBuilder...build();
}
}
So far this works great! However, now my retryer requires a LogPublisher object provided in another module.
I'm trying
public class ToyModule extends AbstractModule {
LogPublisher logPublisher;
#Override
protected void configure() {
requestInjection(logPublisher);
bind(ToyAdapter.class).in(Singleton.class);
bind(Retryer.class).annotatedWith(Names.named("toyRetryer")).toInstance(getToyRetryer());
}
private Retryer getToyRetryer() {
return RetryerBuilder.withLogPublisher(logPublisher).build();
}
}
LogPublisher is provided in another guice module which has alot of other objects that depend on LogPublisher so I'd rather not just merge everything into one giant guice module.
#Provides
#Singleton
public LogPublisher getLogPublisher() {...}
Is this the proper way to do this? I'm getting Java findBugs errors saying unwritten field so I'm thinking I'm doing it wrong.
Declare your Retryer with help of #Provides/#Named annotations.
#Provides
#Singleton
#Named("toyRetryer")
public Retryer getToyRetryer(LogPublisher logPublisher) {
return RetryerBuilder.withLogPublisher(logPublisher).build();
}
Have an interface that needs many implementations to be bound to it.
Going for the following design because of many constraints (May not seem good, please ignore the design).
Is it possible to create an injector for another module installed in current module while still running the configure() method for the current module.?
public class CurrentModule extends AbstractModule{
#Override
protected void configure() {
install(new OtherModule());
final someInterface getInstance = methodToGetInstance();
bind(SomeInterface.class).to(getInstance);
}
public SomeInterface methodToGetInstance() {
Injector injector = Guice.createInjector(new OtherModule());
return new ClassImplementingSomeInterface(injector.getInstance(dependency));
}
}
Yes, what you ask is possible with provider methods. This is how you should do it:
class CurrentModule extends AbstractModule {
#Override protected void configure() {
install(new OtherModule());
// Optional, but it's good to write it if the dependency becomes missing from OtherModule.
requireBinding(DependencyFromOtherModule.class);
}
#Singleton
#Provides SomeInterface createSomeInterface(DependencyFromOtherModule dependency) {
return new ClassImplementingSomeInterface(dependency);
}
}
Let's say I have a module:
Module extends AbstractModule
{
#Override
protected void configure()
{
bind(String.class).
annotatedWith(Names.named("annotation")).
toInstance("DELIRIOUS");
}
}
and I want to test the module and check if it injects the right value in a String field annotated with Names.named("annotation") without having a class and a field but obtaining the value directly from the injector:
#Test
public void test()
{
Injector injector = Guice.createInjector(new Module());
// THIS IS NOT GOING TO WORK!
String delirious = injector.getInstance(String.class);
assertThat(delirious, IsEqual.equalTo("DELIRIOUS");
}
injector.getInstance(Key.get(String.class, Names.named("annotation")));
I'm using the following method
public <T> T getInstance(Class<T> type, Class<? extends Annotation> option) {
final Key<T> key = Key.get(type, option);
return injector.getInstance(key);
}
for this. In general, you still have the problem of creating the annotation instance, but here Names.named("annotation") works.
I have some sample code which is using factories. I'd like to clean up the code by removing the factories and use Guice instead. I attempted to do this but I hit a small roadblock. I am really new to Guice, so I am hoping someone can help me out here.
Existing client code (Using factories):
public class MailClient {
public static void main(String[] args) {
MailConfig config = MailConfigFactory.get();
config.setHost("smtp.gmail.com");
Mail mail = MailFactory.get(config);
mail.send();
}
}
My attempt to refactor using Guice:
//Replaces existing factories
public class MailModule extends AbstractModule {
#Override
protected void configure() {
bind(Mail.class)
.to(MailImpl.class);
bind(MailConfig.class)
.to(MailConfigImpl.class);
}
}
public class MailImpl implements Mail {
private final MailConfig config;
#Inject
public MailImpl(MailConfig config) {
this.config = config;
}
public void send() { ... }
}
public class MailClient {
public static void main(String[] args) {
MailModule mailModule = new MailModule();
Injector injector = Guice.createInjector(mailModule);
MailConfig config = injector.getInstance(MailConfig.class);
config.setHost("smtp.gmail.com");
Mail mail = //??
mail.send();
}
}
How would I construct an instance of MailImpl using the object config in my revised MailClient? Should I be using Guice in this way?
Take a look at AssistedInject. It appears to address this problem.
2 solutions are possible:
1) bind the config as a guice object also, including its host parameter. then just inject Mail, in your main method you cna ignore the fact that mail has further dependencies.
2) mail must be configured individually for each send (recipient?). then you have no choice, but create it yourself using MailFactory.
You can do everything in MailModule as follows:
public class MailModule extends AbstractModule {
#Override
protected void configure() {
... // other bindings
}
#Provides
MailConfig getMailConfig( ... ) {
MailConfig config = new MailConfig( ... );
config.setHost("smtp.gmail.com");
config;
}
}
If you want a singleton MailConfig, add the #Singleton annotation to getMailConfig(), and Bob's your uncle.
Note that arguments to getMailConfig must be bound. When you bind commonly used types like String, be sure to add a binding annotation.