Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

With or without bean definition in applicationContext.xml

 
sam White
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • 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
 
Sean Clark
Rancher
Posts: 377
Android Java Spring
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic