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