假设我有 A 级。
class A {
private String s;
public A(String s) {
this.s = s;
}
}
我想将 A 注入(inject)到 B 类中。
到目前为止,我一直在注入(inject)没有构造函数参数的类,例如
class B {
@Inject
private A a;
}
但我不知道如何注入(inject)带有构造函数参数的类。 我怎样才能做到这一点?
最佳答案
我认为在你的例子中A
将是一个原型(prototype)bean,因为它有一个你必须提供的参数。因为您必须提供参数,所以您不能像单例一样简单地注入(inject) bean。您可以注入(inject)BeanContext
并调用createBean
。例如:beanContext.createBean(A.class, "some string value")
。这需要使用 @Prototype
注释 A
以及创建者应使用 @Parameter
提供的任何构造函数参数。
关于java - 有没有办法可以在 micronaut 中注入(inject)一个其构造函数具有参数的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59007113/