Options for using @Named() with no prior name knowledge in Guice of the Named value?

Skip to first unread message


Sep 29, 2020, 4:58:43 AM9/29/20
to google...@googlegroups.com
Short version:

How can I do this generically without telling Guice ahead of time what the string values in the @Named annotation are?

@Named("contentServer")  // "contentServer" not known by Guice at compile time
public SSHClient contentServer;

@Named("testnode1")  // "testnode1" not known by Guice at compile time
public SSHClient testnode1;

Where "contentServer" and 'testnode1' map to a set of properties loaded at runtime, such as:

#From test.properties file



Longer Version:
I'm using TestNG with the @Guice annotation and a single GuiceModule class with a single @Provides method (below) to facilitate injecting SSH Client instances into the test classes.  The Guice Module is shared and used by many test classes, each having different SSHClient needs.  My current Guice provider only supports a single SSHClient node (no @Named support) based on a common set of properties and looks like the following:

//From GuiceModule 
Properties config = null;

protected void configure() {
    Names.bindProperties(binder(), config);

public Properties ConfigProvider() {
    return config;

//GuiceModule SSHCLient provider method
public SSHClient sshClientProvider(@Named("CONFIG") Properties config) {
    String hostname;
    String username;
    String password;

    hostname = config.getProperty("ssh.hostname");
    username = config.getProperty("ssh.username");
    password = config.getProperty("ssh.password");
    SSHClient ssh = null;

    if (hostname != null && username != null && password != null) {
        try {
            ssh = new SSHClient(hostname, username, password);
        } catch (Exception ex) {
            System.out.println(String.format("[WARN] Exception creating SSHClient instance: host %s: user %s:  Message: %s", hostname, username, ex.getMessage()));
    return ssh;

I hoped to make it more dynamic based on the properties file definitions to support multiple SSHClient @Named instances using unique prefixes for each node.  The shared Guice module won't know what prefixes are defined because each test implementation uses SSH instances for different purposes.  

I haven't seen any examples that match (in my limited understanding at least) how I could create such providers dynamically at runtime. 

Any pointers/thoughts on how I could support this are much appreciated!

Reply all
Reply to author
0 new messages