Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use @Resource on a constructor?

I was wondering if it possible to use the @Resource annotation on a constructor.

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?

like image 692
Marco Avatar asked Apr 29 '11 10:04

Marco


People also ask

Can we use @autowired on constructor?

You can apply @Autowired to constructors as well. A constructor @Autowired annotation indicates that the constructor should be autowired when creating the bean, even if no <constructor-arg> elements are used while configuring the bean in XML file.

What is difference between @resource and @autowired?

The main difference is is that @Autowired is a spring annotation whereas @Resource is specified by the JSR-250. So the latter is part of normal java where as @Autowired is only available by spring.

What is @resource annotation in Java?

The javax. annotation. Resource annotation is used to declare a reference to a resource; @Resource can decorate a class, a field, or a method.

What is the use of @resource annotation in spring?

The @Resource annotation in spring performs the autowiring functionality. This annotation follows the autowire=byName semantics in the XML based configuration i.e. it takes the name attribute for the injection. Below snippet shows how to use this annotation. This annotation takes an optional name argument.


2 Answers

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.

like image 109
Sean Patrick Floyd Avatar answered Oct 04 '22 05:10

Sean Patrick Floyd


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.

like image 32
Pierre Henry Avatar answered Oct 04 '22 04:10

Pierre Henry