是否可以在构造函数上使用@Resource?

Mar*_*rco 18 java spring autowired spring-annotations

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

我的用例是我想连接一个名为的最后一个字段bar.

public class Foo implements FooBar {

    private final Bar bar;

    @javax.annotation.Resource(name="myname")
    public Foo(Bar bar) {
        this.bar = bar;
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到一条消息,指出@Resource此位置不允许这样做.有没有其他方法可以连接最后一个字段?

Sea*_*oyd 19

从以下来源@Resource:

@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface Resource {
    //...
}
Run Code Online (Sandbox Code Playgroud)

这一行:

@Target({TYPE, FIELD, METHOD})
Run Code Online (Sandbox Code Playgroud)

表示此注释只能放在类,字段和方法上.CONSTRUCTOR不见了.


Rob*_*anu 9

使用@Autowired@Inject.Spring参考文档中介绍了此限制:使用限定符微调基于注释的自动装配:

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

  • 好点子.在Spring 3文档中,我们对此进行了改进,以提及您遇到的问题,请在http://static.springsource.org/spring/docs/3.0.x/reference/beans.html#beans-autowired-annotation中查找提示. -qualifiers (2认同)

Pie*_*nry 9

为了补充罗伯特·蒙特亚努的答案,以供将来参考,这里采用的是如何@Autowired以及@Qualifier在构造函数中的样子:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在这个例子中,bar只是自动装配(即上下文中只有一个bean的bean,所以Spring知道要使用哪个),同时baz有一个限定符告诉Spring我们想要注入哪个类的特定bean.