3

I have a Class which represents a graphical Component. This component displays data from the database.

Now I have some kind of dashboard, which has 12 of my Components above. Of course I want to reuse this component! So I thought, I could use a Custom Annotation with parameters and pass the parameters to a provider. I found some hack on Stackoverflow (http://stackoverflow.com/questions/5704918/custom-guice-binding-annot...) but to be honest, I did not find any documentation how to implement an AnnotationImpl for my Custom Interface.

I do not think, that AssistedInject is what I need here, because I do not like the idea to inject 12x the same Class via AssistedInjection to my constructor.

A No-Go for me is to write an Interface and 12 implementation classes, just for one different parameter.

Has anyone an idea for my issue?

Dominik Obermaier
  • 5,610
  • 4
  • 34
  • 45

1 Answers1

4

I'm not exactly clear on what you're trying to do, but i think Assisted inject might be right for you. Can you not create a ComponentFactory and then, in it's create method, specify this parameter you need? You don't even need to create a concrete implementation of the Factory as Guice will do that for you and you can specify it like this:

install(new FactoryModuleBuilder().build(ComponentFactory.class));

ComponentFactory would look like this:

public interface ComponentFactory {
    Component create(ParameterType parameter);
}

And the Component itself like this:

public class Component {
    @Inject
    public WebClient(@Assisted ParameterType parameter, OtherService service) {
        // etc...
    }
}

Then you pass the ComponentFactory to your Dashboard and it can create (easily) whatever Components it wants.

alpian
  • 4,668
  • 1
  • 18
  • 19
  • 1
    You are absolutely right. I thought about it after your post and it is a clear scenario for Assisted Injection. Thanks for pointing me into the right direction. One suggestion for your binding notation: You could bind a Factory with `install( new FactoryModuleBuilder().build( MyFactory.class ) );` I personally think this notation is more concise :) – Dominik Obermaier Apr 26 '11 at 21:33
  • I much prefer that syntax too. I haven't used Guice 3.0 yet but perhaps it's time to upgrade! – alpian Apr 26 '11 at 21:40