【发布时间】:2019-11-20 04:31:34
【问题描述】:
我正在尝试将 Picocli 与 Spring Boot 2.2 一起使用以将命令行参数传递给 Spring Bean,但不确定如何构造它。例如,我有以下@Command 从命令行指定连接用户名和密码,但是,想使用这些参数来定义一个 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);
}
}
我在这里陷入了一个循环。我需要命令行用户名/密码来实例化我的 JMSPublisherBean,但这些仅在运行时可用,在启动时不可用。
我已经设法通过使用延迟初始化、将ClearJdoCommand bean 注入到配置 bean 并从 Spring 上下文中检索我的run() 中的 JMSPublisherBean 来解决这个问题,但这似乎是一个丑陋的 hack。此外,它迫使我所有的豆子都懒惰,这不是我的偏好。
是否有另一种/更好的方法来实现这一点?
【问题讨论】:
-
这不能回答你的问题,但请注意 kakawait 插件已被github.com/remkop/picocli/tree/master/…取代
标签: spring-boot picocli