I have recently started using Spring framework. I'm confused between when to use @Resource
vs Property argument in xml file (the traditional way). What are the special real use-cases that were considered for designing new Annotations ? Would you advice to shift completely to using Spring Annotations ?

- 441
- 2
- 8
- 27
-
@ryekayo Thanks for info. I have updated my Question. – Ashley Apr 11 '16 at 18:33
2 Answers
Well the difference between @Resource
and @Autowired
is already well explained by a lot of posts, you could also find from my blog.
Basically they are specifying different way to search for a bean before Injection.
@Autowired
will assembled by type before by name in default, whereas @Resource
assembled by name in default then type. They also belong to different jar.
Regarding Property argument in xml file
, it is the way you specifying the value of fields in beans. Say you want to create a bean named SamplePerson
which is an object of a Person
Class, what you need to do in xml
is to tell Spring what the value of field in this object, just like:
Person samplePerson = new Person();
samplePerson.setAge(23);
samplePerson.setName("Rugal");
After creating such a bean, Spring context will place this object inside its container for later usage. Now you could use @Autowired
or @Resource
to inject this samplePerson
bean into a place where needed by using
@Autowired
private Person samplePerson;
Then you will notice this person
object will have its attributes corresponding to your xml definition.
But actually it is tedious to code under XML, I would rather to do all the configuration in Java style, although somebody might argue it is not dynamic enough.
Yes you could totally switch everything from XML configuration to Java configuration. You could get my sample from github.
If you are new to Spring, I will encourage you to use my archetype. You will get a fully integrated code base.

- 2,612
- 1
- 15
- 16
@Autowired is a Spring-specific and @Resource is JSR but current Spring supports both of them. I'd use the JSR one because it will work also without Spring framework so less changes if you decided to use something else). Regarding the annotations vs XML please refer this question Spring annotation-based DI vs xml configuration?
It depends on use cases. For me annotations are easier because they allow to keep everything directly in the java code so it's just self-documenting. But sometimes you may want to use XML (for example if you want to change your configuration without modifying the code itself you can easily switch between different xml locations)
-
According to me the configuration which we might want to change later could be the placeholders or the property arguments were we are setting the values. Rest all the variables should be annotated with @Resource. – Ashley Apr 11 '16 at 18:46