Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mark Spritzler: I never need to call getBean

 
VenkataPrasad Regula
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have found Mark giving the above statement for the question put up by a gentleman at the url http://www.coderanch.com/t/551081/Spring/Obtaining-Spring-beans-elegantly-without. Mark I am really struggling here by corrupting my beans with context.getBean("...") statement. Could you please give me an example code(or an url of it) from which I can make my code more elegant. Thanks
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you be a little more specific about your application.

For instance if I am using Spring MVC, every layer is Spring with beans where when I need a bean in a class, I just inject it through my configuration.

If I was using Struts, There is Spring integration via the ActionSupport class, which gets me the ApplicationContext, then I would have to call getBean, but only in the Struts Action class. All the other classes get the beans injected in through my configuration.

What type of app are you writing.

Mark
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not Mark, but I'll attempt to answer...

A lot of this answer depends on what your code's doing and why it's doing it. If you're developing a Spring MVC web app, it's extremely rare to need to call getBean(), but if you're trying to integrate Spring with some other web framework, or using Spring in a desktop application, there are places you'll need to call getBean() - but it still shouldn't need to be all over the place.

Spring provides several ways to specify what beans to create and how to wire them together - in XML, in Java code, using annotations - what way are you using? It sounds like you've got the bean creation part working - because you can get a reference to it through getBean(). But why aren't you also wiring these beans together when they're created?

Can you give some examples of places you're using getBean()?

Can you post a simple code example with a couple of beans that need to work together and the Spring configuration you'd use to set them up?
 
VenkataPrasad Regula
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mark and Nathan. I got the answer I needed. I have been struggling how to call the beans mainly in the service layers without using getBean(). What I have finally understood is once a bean is called all the beans should get wired into it. I will follow that from now. Thanks a lot.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic