Is it possible to use @Resource on a constructor?

Marco picture Marco · Apr 29, 2011 · Viewed 12.5k times · Source

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?

Answer

Sean Patrick Floyd picture Sean Patrick Floyd · Apr 29, 2011

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.