• 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

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?

Sean Clark
Posts: 377
Android Java Spring
  • 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.

my overalls have superpowers - they repel people who think fashion is important. Tiny ad:
the new thread boost feature brings a LOT of attention to your favorite threads
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!