The moose likes Spring and the fly likes Mark Spritzler: I never need to call getBean Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Spring
Bookmark "Mark Spritzler: I never need to call getBean" Watch "Mark Spritzler: I never need to call getBean" New topic

Mark Spritzler: I never need to call getBean

VenkataPrasad Regula
Ranch Hand

Joined: Jun 30, 2011
Posts: 63
I have found Mark giving the above statement for the question put up by a gentleman at the url 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

Joined: Feb 05, 2001
Posts: 17276

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.


Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
Nathan Pruett

Joined: Oct 18, 2000
Posts: 4121

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?

Write once, run anywhere, because there's nowhere to hide! - /. A.C.
VenkataPrasad Regula
Ranch Hand

Joined: Jun 30, 2011
Posts: 63
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.
I agree. Here's the link:
subject: Mark Spritzler: I never need to call getBean
It's not a secret anymore!