gpt4 book ai didi

java - 如何在 Micronaut cli 应用程序中注入(inject) bean 和创建自定义 bean

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:21:42 24 4
gpt4 key购买 nike

我想在 micronaut cli 应用程序中注入(inject) 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,但没有成功

@工厂 公共(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com