我想在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,但没有成功
@工厂
公共类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

最佳答案

您是否尝试使用@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();
  }
}

关于java - 如何在Micronaut cli应用程序中注入(inject)bean并创建自定义bean,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54225005/

10-12 03:13