作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
@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
}
}
@工厂 公共(public)类 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] 注入(inject)值:com.UtilityCommand
采用的路径:UtilityCommand.someBean
最佳答案
我也遇到过,我注意到我在 main 中使用了 Picocli runner
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
关于java - 如何在 Micronaut cli 应用程序中注入(inject) bean 和创建自定义 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54225005/
我是一名优秀的程序员,十分优秀!