[英]Is there a way you can inject a class whose constructor has parameters in micronaut?
Suppose I have class A. 假设我有A班。
class A {
private String s;
public A(String s) {
this.s = s;
}
}
and I want to inject A into class B. 我想将A注入B类。
So far, I have been injecting classes without constructor parameters like 到目前为止,我一直在注入没有构造函数参数的类,例如
class B {
@Inject
private A a;
}
But I don't know how classes with constructor parameters can be injected. 但是我不知道如何注入带有构造函数参数的类。 How can I do this? 我怎样才能做到这一点?
You need to prepend your constructor with @Inject
to make it injectable. 您需要在构造函数之前添加@Inject
使其可注入。 Please check https://docs.oracle.com/javaee/6/api/javax/inject/Inject.html for documentation and examples. 请检查https://docs.oracle.com/javaee/6/api/javax/inject/Inject.html以获取文档和示例。
Instead of this: 代替这个:
@Singleton
class B {
@Inject
private A a;
}
You could have this: 你可能有这个:
@Singleton
class B {
private A a;
public B(A a) {
this.a = a;
}
}
I think in your example A
would be a prototype bean because it has an argument that you must provide. 我认为在您的示例A
中将是原型bean,因为它具有必须提供的参数。 Because you must provide the argument you can't simply inject the bean like you would a singleton. 因为必须提供参数,所以不能像单例那样简单地注入bean。 You can inject the BeanContext
and call createBean
. 您可以注入BeanContext
并调用createBean
。 For example: beanContext.createBean(A.class, "some string value")
. 例如: beanContext.createBean(A.class, "some string value")
。 That would require A
be annotated with @Prototype
and any constructor parameters that should be provided by the creator with @Parameter
. 这将要求A
带有@Prototype
注释,并且创建者应使用@Parameter
对其提供的任何构造函数参数进行注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.