Reputation: 41
@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
}
}
@Factory public class MyFactory {
@Bean
public SomeBean myBean() {
new SomeBean();
}
}
Simple testcase to check verbose output ##
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: Could not instantiate class com.UtilityCommand: io.micronaut.context.exceptions.DependencyInjectionException: Failed to inject value for field [someBean] of class: com.UtilityCommand
Path Taken: UtilityCommand.someBean
Upvotes: 4
Views: 5185
Reputation: 209
Happened to me also, and I noticed that I used the Picocli runner in main
public static void main(String[] args) {
new CommandLine(commandObject).execute(args);
}
I changed to Micronaut's PicocliRunner and it worked
public static void main(String[] args) {
PicocliRunner.run(commandObject.class,args);
}
Also, I saw this example
Upvotes: 1
Reputation: 76
Have you tried using @Singleton as below:
just annotate you class 'SomeBean' with @Singleton.
@Singleton
public SomeBean {
}
and try to inject this in your utility command class.
Upvotes: 0
Reputation: 1
Have you tried to use the @Requires the annotation?
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();
}
}
Upvotes: 0