Kevin
Kevin

Reputation: 6292

How to pass constructor parameter in Guice

I have a Swing class:

public class PopUpContextMenu extends JPopupMenu {
    public PopUpContextMenu() {
        super();

        JMenuItem loginMenuItem = new LoginMenuItem("Login");
        JMenuItem logoutMenuItem = new LogoutMenuItem("Logout");
        add(loginMenuItem);
        add(logoutMenuItem);
    }
}

I wat to change it to use Guice so that the two "new" statement can be removed. I want something like:

public class PopUpContextMenu extends JPopupMenu {
    @Inject
    public PopUpContextMenu(JMenuItem loginMenuItem, JMenuItem logoutMenuItem) {
        super();
        add(loginMenuItem);
        add(logoutMenuItem);
    }
}

My question is how can I configure bindings in Guice so that I can pass the string "Login" when constructing loginMenuItem and pass string "Logout" when constructing logoutMenuItem?

Many thanks

Upvotes: 1

Views: 1497

Answers (1)

user1697575
user1697575

Reputation: 2848

You could use @Named annotation for that:

In your class:

@Inject
@Named("LOGIN")
JMenuItem loginMenuItem;

@Inject
@Named("LOGOUT")
JMenuItem logoutMenuItem

So then in your Guice module configure() method you do:

bind(JMenuItem.class).annotatedWith(Names.named("LOGIN")).toInstance(new LoginMenuItem("Login"));
bind(JMenuItem.class).annotatedWith(Names.named("LOGOUT")).toInstance(new LoginMenuItem("Logout"));

Upvotes: 1

Related Questions