I'm trying to use Picocli with Spring Boot 2.2 to pass command line parameters to a Spring Bean, but not sure how to structure this. For example, I have the following @Command
to specify a connection username and password from the command line, however, want to use those params to define a Bean:
@Component
@CommandLine.Command
public class ClearJdoCommand extends HelpAwarePicocliCommand {
@CommandLine.Option(names={"-u", "--username"}, description = "Username to connect to MQ")
String username;
@CommandLine.Option(names={"-p", "--password"}, description = "Password to connect to MQ")
String password;
@Autowired
JMSMessagePublisherBean jmsMessagePublisher;
@Override
public void run() {
super.run();
jmsMessagePublisher.publishMessage( "Test Message");
}
}
@Configuration
public class Config {
@Bean
public InitialContext getJndiContext() throws NamingException {
// Set up the namingContext for the JNDI lookup
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, "http-remoting://localhost:8080");
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password);
return new InitialContext(env);
}
@Bean
public JMSPublisherBean getJmsPublisher(InitialContext ctx){
return new JMSPublisherBean(ctx);
}
}
I'm stuck in a bit of a circular loop here. I need the command-line username/password to instantiate my JMSPublisherBean, but these are only available at runtime and not available at startup.
I have managed to get around the issue by using Lazy intialization, injecting the ClearJdoCommand
bean into the Configuration bean and retrieving the JMSPublisherBean in my run()
from the Spring context, but that seems like an ugly hack. Additionally, it forces all my beans to be Lazy, which is not my preference.
Is there another/better approach to accomplish this?