19

我想知道是否可以@Resource在构造函数上使用注释。

我的用例是我想连接一个名为bar.

public class Foo implements FooBar {

    private final Bar bar;

    @javax.annotation.Resource(name="myname")
    public Foo(Bar bar) {
        this.bar = bar;
    }
}

我收到一条消息,指出@Resource此位置不允许使用。还有其他方法可以连接最终字段吗?

4

3 回答 3

24

从来源@Resource

@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface Resource {
    //...
}

这一行:

@Target({TYPE, FIELD, METHOD})

意味着这个注解只能放在Classes、Fields和Methods上。CONSTRUCTOR不见了。

于 2011-04-29T11:07:44.987 回答
11

为了补充 Robert Munteanu 的回答并供将来参考,以下是使用@Autowiredand @Qualifieron 构造函数的外观:

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.

于 2016-09-16T14:02:04.487 回答
9

使用@Autowired@Inject。Spring 参考文档中涵盖了此限制: Fine-tuning annotation-based autowiring with qualifiers

@Autowired 适用于字段、构造函数和多参数方法,允许在参数级别通过限定符注释缩小范围。相比之下,@Resource 仅支持具有单个参数的字段和 bean 属性设置器方法。因此,如果您的注入目标是构造函数或多参数方法,请坚持使用限定符。

于 2011-04-29T11:01:02.590 回答