Win a copy of Learn Java with Math: Using Fun Projects and Games this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Junilu Lacar
  • Martin Vashko
  • Jeanne Boyarsky
  • Tim Cooke
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
  • salvin francis
  • Piet Souris

With or without bean definition in applicationContext.xml

Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I found in some cases, with SpringFramework, it defined Dao bean definition in applicationContext.xml file as shown below:

<bean id="userDAO" class="" />
<bean id="stateDAO" class="" />
<bean id="countryDAO" class="" />

but sometimes I heard we don't need all these bean mapping in applicaitonContext.xml file, just need Spring annotation @autowired.

In which cases should I use annotatino @autowired , and when should I add bean definition in applicationContext.xml file?

Posts: 377
Android Spring Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

@Autowired is the annotation used for indicating that you want an instance variable (or setter for one) or a constructor to be autowired using the beans that are available within the application context.

If you want to initialise the beans using annotations you have to mark the class with one of Spring's stereotype annotations:- @Component, @Repository, @Service, or @Controller and also remember to put <context:component-scan base-package="org.example"/> into your applicationContext.xml file so that these annotations are looked for.
More information can be found here spring docs.

Why you would do this is down to what is prefered.
Do you want lots of xml files to maintain? Or do you want to maintain the classes? Annotations sometimes make it harder to know what's going on due to the "magic" that tends to go on in the background rather than you having to explicitly create all your beans.

Personally I'm in favour.

The problems of the world fade way as you eat a piece of pie. This tiny ad has never known problems:
Java file APIs (DOC, XLS, PDF, and many more)
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!