I want to inject beans in micronaut cli application
Example: Below is my Command Class
@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
}
}
I tried creating Factory class as per documentation(https://docs.micronaut.io/latest/api/io/micronaut/context/annotation/Factory.html) and created bean, but no luck
@Factory public class MyFactory {
@Bean
public SomeBean myBean() {
new SomeBean();
}
}
I came to this when I ran my tests.
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!"));
}
}
Im getting following exception
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