*
The moose likes Spring and the fly likes With or without bean definition in applicationContext.xml Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Spring
Bookmark "With or without bean definition in applicationContext.xml" Watch "With or without bean definition in applicationContext.xml" New topic
Author

With or without bean definition in applicationContext.xml

sam White
Ranch Hand

Joined: Feb 18, 2011
Posts: 208
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

Joined: Jul 15, 2009
Posts: 377

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

I love this place!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: With or without bean definition in applicationContext.xml