首页 > 解决方案 > 如何在 Micronaut cli 应用程序中注入 bean 和创建自定义 bean

问题描述

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

示例:下面是我的命令类

@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)创建工厂类并创建了bean,但没有运气

@Factory 公共类 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:无法为类的字段 [someBean] 注入值:com.UtilityCommand

采用的路径:UtilityCommand.someBean

标签: javacommand-linemicronaut

解决方案


也发生在我身上,我注意到我在 main 中使用了 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);
}

另外,我看到了这个例子


推荐阅读