google / google/guice

Provider Factory and then Inject what the Provider returns

Open
#655 2 comments 0 reactions 0 assignees View on GitHub
imported
Dominant language
Java
Stars
12.7k
Forks
1.7k
Avg merge
11m
Merged PRs (30d)
2

Description

_From [rkapsi](https://code.google.com/u/116755208212771764698/) on September 26, 2011 15:09:54_

I think this is partly related to Issue #131 , FactoryModuleBuilder & Co but with a slightly different twist. I'm not interested in the Factories themselves (which seems to be the purpose of FactoryModuleBuilder and FactoryProvider) but would rather tell Guice how to create Objects for me with some arguments that I provide and with some arguments that Guice can inject for me.

Here is an example where I provide the type of my POJO, Guice injects some additional stuff to my factory method and I do something with it (e.g. use the arguments to read some resource such as JSON/XML and create a POJO from that).

public class ConfigModule extends AbstractModule {
  `@`Override
  protected void configure() {
    bind(PicasaConfig.class).toFactory(new ConfigFactory<PicasaConfig>(PicasaConfig.class));
    bind(FlickrConfig.class).toFactory(new ConfigFactory<FlickrConfig>(FlickrConfig.class));
  }
}

public class ConfigFactory<T> {
  
  private final Class<T> type;
  
  public ConfigFactory(Class<T> type) {
    this.type = type;
  }
  
  `@`Provides `@`Inject
  public T create(`@`Named("mv.config.cl") ClassLoader loader, `@`Named("my.env") String environment) {
    return DoSomeMagic.newInstance(loader, environment, type);
  }
}

`@`Singleton
public class PicasaProcessor {
  
  private final PicasaConfig config;
  
  `@`Inject
  public PicasaProcessor(PicasaConfig config) {
    this.config = config;
  }
}

_Original issue: http://code.google.com/p/google-guice/issues/detail?id=655_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.