java - 如何在 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
解决方案
也发生在我身上,我注意到我在 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);
}
另外,我看到了这个例子
推荐阅读
- python - 机器学习的数据编码
- go - 将变量传递给回调函数
- reactjs - 使用流项目为 javascript 运行 react-codemod 时出错
- excel - VBA使用工作表中的usedrows用Null填充空白单元格
- angularjs - 控制器内部的 Webpack 生产环境不起作用?
- java - ORMLite QueryBuilder.orderByRaw(String, SelectArg) 忽略 QueryBuilder.queryRaw() 上的 SelectArg
- javascript - 按 MySQL SELECT COUNT(*) GROUP BY 显示条形图
- vue.js - vuetify 2.0 v-data-table 加载道具在加载后未禁用
- android - SoundPool play()... 在线程或主 UI 线程中更好?
- c# - c# return System.Byte[] ,我想用python打开