• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

With or without bean definition in applicationContext.xml

 
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

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

<bean id="userDAO" class="com.xxx.persistence.jpa.UserJpaDAO" />
<bean id="stateDAO" class="com.xxx.persistence.jpa.StateJpaDAO" />
<bean id="countryDAO" class="com.xxx.persistence.jpa.CountryJpaDAO" />

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?

Thanks
Sam
 
Rancher
Posts: 377
Android Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey,

@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.

Sean
reply
    Bookmark Topic Watch Topic
  • New Topic