Short version:
How can I do this generically without telling Guice ahead of time what the string values in the @Named annotation are?
@Inject
@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
ssh.clients=contentServer,testnode01
contentServer.ssh.username=<csUser>
contentServer.ssh.password=<csPwd>
testnode01.ssh.username=<nodeuser1>
testnode01.ssh.password=<nodepwd1>
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;
@Override
protected void configure() {
loadConfig();
Names.bindProperties(binder(), config);
}
@Provides
@Named("CONFIG")
@Singleton
public Properties ConfigProvider() {
return config;
}
//GuiceModule SSHCLient provider method
@Provides
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!
-Jeff