Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (10.2k points)
Which annotation, @Resource or @Autowired (Spring-specific) should I use in DI?

I have successfully used both in the past, @Resource(name="blah") and @Autowired @Qualifier("blah")

My instinct is to stick with the @Resource tag since it's been ratified by the JSR people.

Does anyone have strong thoughts on this?

1 Answer

0 votes
by (46k points)

In spring pre-3.0 it doesn't mean which item.

In spring 3.0 there's an aid for the standard (JSR-330) annotation @javax.inject.Inject - practice it, with a blend of @Qualifier. Note that spring now also helps the @javax.inject.Qualifier meta-annotation:



public @interface YourQualifier {}

So you can possess

<bean class="com.pkg.SomeBean">

   <qualifier type="YourQualifier"/>





public class SomeBean implements Foo { .. }

And then:

@Inject @YourQualifier private Foo foo;

This creates less application of String-names, which can be misspelled and are more difficult to manage.

both, without defining any attributes of the annotation, inject by type. The exception is:

  • @Resource allows you to specify a name of the injected bean
  • @Autowired allows you to mark it as non-mandatory.

Related questions

0 votes
1 answer
asked Jul 30, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 26, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
asked Aug 6, 2019 in Java by Krishna (2.6k points)

Browse Categories