开发者

Is it possible to use @Resource on a constructor?

I was wondering if it possible to use the @Resource annotation on a constructo开发者_C百科r.

My use case is that I want to wire a final field called 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?


From the source of @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.


To complement Robert Munteanu's answer and for future reference, here is how the use of @Autowired and @Qualifier on constructor looks :

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.


Use @Autowired or @Inject. This limitation is covered in the Spring reference documentation: Fine-tuning annotation-based autowiring with qualifiers:

@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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜