@command(name = "com/utils", description = "..",
mixinStandardHelpOptions = true, header = {..})
public class UtilityCommand implements Runnable {
@Inject
SomeBean somebean;
public void run() {
somebean.method1();
}
}
# Now I want to create Singleton bean using below syntax #
@Singleton
public class SomeBean {
@Inject RxHttpClient client;
void method1(){
client.exchange(); // Rest call goes here
}
}
@工厂 公共类MyFactory {
@Bean
public SomeBean myBean() {
new SomeBean();
}
}
简单的测试用例,用于检查详细的输出##
public class UtilityCommandTest {
@test
public void testWithCommandLineOption() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) {
**ctx.registerSingleton(SomeBean.class,true);**
String[] args = new String[] { "-v"};
PicocliRunner.run(UtilityCommand.class, ctx, args);
assertTrue(baos.toString(), baos.toString().contains("Hi!"));
}
}
picocli.CommandLine $ InitializationException:无法实例化com.UtilityCommand类:io.micronaut.context.exceptions.DependencyInjectionException:无法为类com.UtilityCommand的字段[someBean]注入值。
采用的路径:UtilityCommand.someBean
答案 0 :(得分:1)
也发生在我身上,我注意到我在主赛中使用了Picocli跑步器
public static void main(String[] args) {
new CommandLine(commandObject).execute(args);
}
我改用Micronaut的PicocliRunner,它起作用了
public static void main(String[] args) {
PicocliRunner.run(commandObject.class,args);
}
我也看到了这个example
答案 1 :(得分:0)
您是否尝试过使用@Requires注释?
command(name = "com/utils", description = "..",
mixinStandardHelpOptions = true, header = {..})
@Requires(beans = SomeBean.class)
public class UtilityCommand implements Runnable {
@Inject
SomeBean somebean;
public void run() {
somebean.method1();
}
}
答案 2 :(得分:0)
您是否尝试过使用@Singleton,如下所示:
只需使用@Singleton注释您的“ SomeBean”类。
@Singleton
public SomeBean {
}
,然后尝试将其插入实用程序命令类。