如何在Micronaut cli应用程序中注入bean并创建自定义bean

时间:2019-01-16 20:38:50

标签: java command-line micronaut

我想在micronaut cli应用程序中注入豆类

示例:以下是我的命令类

@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
}

}

我尝试根据文档(https://docs.micronaut.io/latest/api/io/micronaut/context/annotation/Factory.html)创建Factory类并创建了bean,但是没有运气

@工厂  公共类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

3 个答案:

答案 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 {    
} 

,然后尝试将其插入实用程序命令类。