Using SilkDI to build a simple swing app

39 views
Skip to first unread message

Marco Bagnaresi

unread,
May 17, 2014, 8:11:06 AM5/17/14
to sil...@googlegroups.com
Hi. I'm trying to build a simple swing app, and i'm trying to use SilkDI for dependency injection.

Many concepts behind silk sound very logical to me (no field injection, no setter injection, etc). I simply do not understand how to use it for my needs.

I have a gui that is builded "in cascade". So i have constructors with many arguments of the same type.

eg :

class FileMenuBuilder implements IMenuProvider {

private JMenu fileMenu_;

public FileMenuBuilder(ActionListener fileOpenListener, ActionListener fileSaveListener, ActionListener fileCloseListener, ActionListener fileQuitListener)
{
   // ... actually build the menu
}


@Override
public JMenu getMenu() {
return fileMenu_;
}

}


Somewhere there will also be a EditMenuBuilder, HelpMenuBuilder, etc ... and a final MenuBuilder that takes all the JMenu and "assembles" the JMenuBar.
It would be illogical to me to extend JMenu since i'm just constructing the gui of my app (and not adding new features to the class JMenu).
But i have many parameters of the same type. How can i tell SilkDI to use the declared parameters in a particolar order?
And also : how can i tell silk to use the getMenu object of my FileMenuBuilder, EditMenuBuilder, HelpMenuBuilder for constructing my MenuBuilder instance?

Thanks for the reply.


-Marco

Jan Bernitt

unread,
May 17, 2014, 1:46:31 PM5/17/14
to sil...@googlegroups.com

Hi Marco,

you can use the toConstructor() method with arguments that describe your different listeners. Since they are all of the same type the order will be the one given in the bind declaration.
I added a test https://github.com/jbee/silk/blob/master/src/test/se/jbee/inject/bind/TestSpecificImplementationBinds.java that shows the scenario using different alternatives to construct the actual instances of the different listeners or actions in my example. 

I assume that your IMenuProvider interface has the getMenu() method. Then you could just do the same - injecting all the IMenuProvider implementers into the MenuBuilder and call the getMenu() somewhere in there. Otherwise you could just Inspect or write a Supplier or Factory but I wouldn't recommend that.

If you really just build a simple swing app why not just glue this together manually? From your example I don't see why a DI tool should make your life easier or better. Or consider to have one method that is composing your menu altogether receiving all its dependencies as arguments. Then you could use inspection as shown here https://github.com/jbee/silk/blob/master/src/test/se/jbee/inject/bind/TestInspectorBinds.java to bind that method as a "factory method". Having the DI tool involved in the menu swing wiring maybe is an overly usage.  

Cheers
Jan
Reply all
Reply to author
Forward
0 new messages