0 votes
1 view
in Java by (7.9k 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 (39.8k 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:

@Qualifier

@Retention(RUNTIME)

public @interface YourQualifier {}

So you can possess

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

   <qualifier type="YourQualifier"/>

</bean>

or

@YourQualifier

@Component

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
0 votes
1 answer
0 votes
1 answer
asked Oct 26 in Java by Anvi (7.9k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...