ramgopalcheedu
ramgopalcheedu

Reputation: 41

How to inject beans and create custom beans in Micronaut cli application

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

Upvotes: 4

Views: 5185

Answers (3)

YoShade
YoShade

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

Mohit Gupta
Mohit Gupta

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

eliana
eliana

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

Related Questions