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?
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.
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.
The javax. annotation. Resource annotation is used to declare a reference to a resource; @Resource can decorate a class, a field, or a method.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With