java 是否可以在构造函数上使用@Resource?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5831128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to use @Resource on a constructor?
提问by Marco
I was wondering if it possible to use the @Resource
annotation on a constructor.
我想知道是否可以@Resource
在构造函数上使用注释。
My use case is that I want to wire a final field called bar
.
我的用例是我想连接一个名为bar
.
public class Foo implements FooBar {
private final Bar bar;
@javax.annotation.Resource(name="myname")
public Foo(Bar bar) {
this.bar = bar;
}
}
I get a message that the @Resource
is not allowed on this location. Is there any other way I could wire the final field?
我收到一条消息,@Resource
该位置不允许。有没有其他方法可以连接最后一个字段?
回答by Sean Patrick Floyd
From the source of @Resource
:
从来源@Resource
:
@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface Resource {
//...
}
This line:
这一行:
@Target({TYPE, FIELD, METHOD})
means that this annotation can only be placed on Classes, Fields and Methods. CONSTRUCTOR
is missing.
意味着这个注解只能放在类、字段和方法上。CONSTRUCTOR
不见了。
回答by Pierre Henry
To complement Robert Munteanu's answer and for future reference, here is how the use of @Autowired
and @Qualifier
on constructor looks :
为了补充 Robert Munteanu 的回答并供将来参考,以下是构造函数@Autowired
和@Qualifier
on的使用方式:
public class FooImpl implements Foo {
private final Bar bar;
private final Baz baz;
@org.springframework.beans.factory.annotation.Autowired
public Foo(Bar bar, @org.springframework.beans.factory.annotation.Qualifier("thisBazInParticular") Baz baz) {
this.bar = bar;
this.baz = baz;
}
}
In this example, bar
is just autowired (i.e. there is only one bean of that class in the context so Spring knows which to use), while baz
has a qualifier to tell Spring which particular bean of that class we want injected.
在这个例子中,bar
它只是自动装配的(即在上下文中只有那个类的一个 bean,所以 Spring 知道要使用哪个),而baz
有一个限定符来告诉 Spring 我们想要注入那个类的哪个特定 bean。
回答by Robert Munteanu
Use @Autowired
or @Inject
. This limitation is covered in the Spring reference documentation: Fine-tuning annotation-based autowiring with qualifiers:
使用@Autowired
或@Inject
。Spring 参考文档中涵盖了此限制:使用限定符微调基于注释的自动装配:
@Autowired applies to fields, constructors, and multi-argument methods, allowing for narrowing through qualifier annotations at the parameter level. By contrast, @Resource is supported only for fields and bean property setter methods with a single argument. As a consequence, stick with qualifiers if your injection target is a constructor or a multi-argument method.
@Autowired 适用于字段、构造函数和多参数方法,允许通过参数级别的限定符注释来缩小范围。相比之下,@Resource 仅支持带有单个参数的字段和 bean 属性 setter 方法。因此,如果您的注入目标是构造函数或多参数方法,请坚持使用限定符。