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

4

我希望在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 public class 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


我不是很确定,因为我刚接触Micronaut,但我认为一个类需要成为bean才能成为注入其他bean的候选对象,所以您需要对UtilityCommand进行注释以使其成为bean。 - Ivan Perales M.
3个回答

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

0
你尝试过使用以下的@Singleton吗:
只需在你的类"SomeBean"上注释@Singleton。
@Singleton
public SomeBean {    
} 

然后尝试将其注入到您的实用命令类中。


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();
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接