Take the 2-minute tour ×

I asked a general Spring question: Auto-cast Spring Beans and had multiple people respond that calling Spring's ApplicationContext.getBean() should be avoided as much as possible. Why is that?

How else should I gain access to the beans I configured Spring to create?

I'm using Spring in a non-web application and had planned on accessing a shared ApplicationContext object as described by LiorH.


I accept the answer below, but here's an alternate take by Martin Fowler who discusses the merits of Dependency Injection vs. using a Service Locator (which is essentially the same as calling a wrapped ApplicationContext.getBean()).

In part, Fowler states, "With service locator the application class asks for it [the service] explicitly by a message to the locator. With injection there is no explicit request, the service appears in the application class - hence the inversion of control. Inversion of control is a common feature of frameworks, but it's something that comes at a price. It tends to be hard to understand and leads to problems when you are trying to debug. So on the whole I prefer to avoid it [Inversion of Control] unless I need it. This isn't to say it's a bad thing, just that I think it needs to justify itself over the more straightforward alternative."

share|improve this question

12 Answers 12

up vote 91 down vote accepted

I mentioned this in a comment on the other question, but the whole idea of Inversion of Control is to have none of your classes know or care how they get the objects they depend on. This makes it easy to change what type of implementation of a given dependency you use at any time. It also makes the classes easy to test, as you can provide mock implementations of dependencies. Finally, it makes the classes simpler and more focused on their core responsibility.

Calling ApplicationContext.getBean() is not Inversion of Control! While it's still easy to change what implemenation is configured for the given bean name, the class now relies directly on Spring to provide that dependency and can't get it any other way. You can't just make your own mock implementation in a test class and pass that to it yourself. This basically defeats Spring's purpose as a dependency injection container.

Everywhere you want to say:

MyClass myClass = applicationContext.getBean("myClass");

you should instead, for example, declare a method:

public void setMyClass(MyClass myClass) {
   this.myClass = myClass;

And then in your configuration:

<bean id="myClass" class="MyClass">...</bean>

<bean id="myOtherClass" class="MyOtherClass">
   <property name="myClass" ref="myClass"/>

Spring will then automatically inject myClass into myOtherClass.

Declare everything in this way, and at the root of it all have something like:

<bean id="myApplication" class="MyApplication">
   <property name="myCentralClass" ref="myCentralClass"/>
   <property name="myOtherCentralClass" ref="myOtherCentralClass"/>

MyApplication is the most central class, and depends at least indirectly on every other service in your program. When bootstrapping, in your main method, you can call applicationContext.getBean("myApplication") but you should not need to call getBean() anywhere else!

share|improve this answer
Is there anything related to this that works with just annotations when creating a new MyOtherClass() object? I know about @Autowired, but I've only ever used it on fields and it breaks on new MyOtherClass().. –  Tim Jul 20 '09 at 16:09
It's not true that ApplicationContext.getBean() is not IoC. Niether is it mandatory to have all your classes instantiated by Spring. That is inappropriate dogma. If the ApplicationContext is itself injected, then it's perfectly fine to ask it to instantiate a bean in this way - and the beans it creates can be different implementations based on the ApplicationContext initially injected. For instance, I have a scenario where I dynamically create new bean instances based on a bean name that is unknown at compile time but matches one of the implementations defined in my spring.xml file. –  Alex Worden Jan 25 '11 at 20:20
Agree with Alex, i have the same issue, where a factory class will only know which bean or implementation to use at run time via user interaction, i think this is where the ContextAware interface comes in –  Ben Dec 20 '12 at 12:22
@herman: I don't know about Spring because I haven't used it in a long time, but in JSR-330/Guice/Dagger, you'd do this by injecting a Provider<Foo> instead of a Foo and calling provider.get() every time you need a new instance. No reference to the container itself, and you can easily create a Provider for testing. –  ColinD Jun 19 '13 at 4:59
@aloplop85: The main method (or more generally, the "entry point", which is often something other than a main method in, say, a web application) would be in your external application. It shouldn't matter where the classes you want to use are, in a jar or in the application itself. When the application runs, they'll all be on the classpath. –  ColinD Jul 8 '13 at 16:07

Reasons to prefer Service Locator over Inversion of Control (IoC) are:

  1. Service Locator is much, much easier for other people to following in your code. IoC is 'magic' but maintenance programmers must understand your convoluted Spring configurations and all the myriad of locations to figure out how you wired your objects.

  2. IoC is terrible for debugging configuration problems. In certain classes of applications the application will not start when misconfigured and you may not get a chance to step through what is going on with a debugger.

  3. IoC is primarily XML based (Annotations improve things but there is still a lot of XML out there). That means developers can't work on your program unless they know all the magic tags defined by Spring. It is not good enough to know Java anymore. This hinders less experience programmers (ie. it is actually poor design to use a more complicated solution when a simpler solution, such as Service Locator, will fulfill the same requirements). Plus, support for diagnosing XML problems is far weaker than support for Java problems.

  4. Dependency injection is more suited to larger programs. Most of the time the additional complexity is not worth it.

  5. Often Spring is used in case you "might want to change the implementation later". There are other ways of achieving this without the complexity of Spring IoC.

  6. For web applications (Java EE WARs) the Spring context is effectively bound at compile time (unless you want operators to grub around the context in the exploded war). You can make Spring use property files, but with servlets property files will need to be at a pre-determined location, which means you can't deploy multiple servlets of the same time on the same box. You can use Spring with JNDI to change properties at servlet startup time, but if you are using JNDI for administrator-modifiable parameters the need for Spring itself lessens (since JNDI is effectively a Service Locator).

  7. With Spring you can lose program Control if Spring is dispatching to your methods. This is convenient and works for many types of applications, but not all. You may need to control program flow when you need to create tasks (threads etc) during initialization or need modifiable resources that Spring didn't know about when the content was bound to your WAR.

Spring is very good for transaction management and has some advantages. It is just that IoC can be over-engineering in many situations and introduce unwarranted complexity for maintainers. Do not automatically use IoC without thinking of ways of not using it first.

share|improve this answer
Plus - your ServiceLocator can always use IoC from Spring, abstracting your code from being dependent on Spring, littered with Spring annotations, and undecipherable magik. I've recently ported a bunch of code to GoogleAppEngine where Spring isn't supported. I wish I'd hidden all IoC behind a ServiceFactory in the first place! –  Alex Worden Jan 25 '11 at 20:29

One of the coolest benefits of using something like Spring is that you don't have to wire your objects together. Zeus's head splits open and your classes appear, fully formed with all of their dependencies created and wired-in, as needed. It's magical and fantastic.

The more you say ClassINeed classINeed = (ClassINeed)ApplicationContext.getBean("classINeed");, the less magic you're getting. Less code is almost always better. If your class really needed a ClassINeed bean, why didn't you just wire it in?

That said, something obviously needs to create the first object. There's nothing wrong with your main method acquiring a bean or two via getBean(), but you should avoid it because whenever you're using it, you're not really using all of the magic of Spring.

share|improve this answer
+1 for Zeus's head splitting open –  Olivier May 1 '09 at 18:09
Zeus's head, growse. :) –  Prof. Falken May 22 '11 at 13:04
But the OP isn't saying "ClassINeed" he's saying "BeanNameINeed" -- which allows the IoC container to create an instance on any class configured in any manner. Perhaps its more like the "service locator" pattern than IoC, but it still results in loose coupling. –  HDave Aug 12 '13 at 21:50

It's true that including the class in application-context.xml avoids the need to use getBean. However, even that is actually unnecessary. If you are writing a standalone application and you DON'T want to include your driver class in application-context.xml, you can use the following code to have Spring autowire the driver's dependencies:

public class AutowireThisDriver {

    private MySpringBean mySpringBean;    

    public static void main(String[] args) {
       AutowireThisDriver atd = new AutowireThisDriver(); //get instance

       ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
                  "/WEB-INF/applicationContext.xml"); //get Spring context 

       //the magic: auto-wire the instance with all its dependencies:
                  AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);        

       // code that uses mySpringBean ...
       mySpringBean.doStuff() // no need to instantiate - thanks to Spring

    public void setMySpringBean(MySpringBean bean) {
       this.mySpringBean = bean;    

I've needed to do this a couple of times when I have some sort of standalone class that needs to use some aspect of my app (eg for testing) but I don't want to include it in application-context because it is not actually part of the app. Note also that this avoids the need to look up the bean using a String name, which I've always thought was ugly.

share|improve this answer
I was able to use this method successfully with the @Autowired annotation also. –  blong Mar 26 '13 at 21:46

The motivation is to write code that doesn't depend explicitly on Spring. That way, if you choose to switch containers, you don't have to rewrite any code.

Think of the container as something is invisible to your code, magically providing for its needs, without being asked.

Dependency injection is a counterpoint to the "service locator" pattern. If you are going to lookup dependencies by name, you might as well get rid of the DI container and use something like JNDI.

share|improve this answer

Using @Autowired or ApplicationContext.getBean() is really the same thing. In both ways you get the bean that is configured in your context and in both ways your code depends on spring. The only thing you should avoid is instantiating your ApplicationContext. Do this only once! In other words, a line like

ApplicationContext context = new ClassPathXmlApplicationContext("AppContext.xml");

should only be used once in your application.

share|improve this answer

The idea is that you rely on dependency injection (inversion of control, or IoC). That is, your components are configured with the components they need. These dependencies are injected (via the constructor or setters) - you don't get then yourself.

ApplicationContext.getBean() requires you to name a bean explicitly within your component. Instead, by using IoC, your configuration can determine what component will be used.

This allows you to rewire your application with different component implementations easily, or configure objects for testing in a straightforward fashion by providing mocked variants (e.g. a mocked DAO so you don't hit a database during testing)

share|improve this answer

Others have pointed to the general problem (and are valid answers), but I'll just offer one additional comment: it's not that you should NEVER do it, but rather that do it as little as possible.

Usually this means that it is done exactly once: during bootstrapping. And then it's just to access the "root" bean, through which other dependencies can be resolved. This can be reusable code, like base servlet (if developing web apps).

share|improve this answer

One of Spring premises is avoid coupling. Define and use Interfaces, DI, AOP and avoid using ApplicationContext.getBean() :-)

share|improve this answer

There is another time when using getBean makes sense. If you're reconfiguring a system that already exists, where the dependencies are not explicitly called out in spring context files. You can start the process by putting in calls to getBean, so that you don't have to wire it all up at once. This way you can slowly build up your spring configuration putting each piece in place over time and getting the bits lined up properly. The calls to getBean will eventually be replaced, but as you understand the structure of the code, or lack there of, you can start the process of wiring more and more beans and using fewer and fewer calls to getBean.

share|improve this answer

I've only found two situations where getBean() was required:

Others have mentioned using getBean() in main() to fetch the "main" bean for a standalone program.

Another use I have made of getBean() are in situations where an interactive user configuration determines the bean makeup for a particular situation. So that, for instance, part of the boot system loops through a database table using getBean() with a scope='prototype' bean definition and then setting additional properties. Presumably, there is a UI that adjusts the database table that would be friendlier than attempting to (re)write the application context XML.

share|improve this answer

however, there are still cases where you need the service locator pattern. for example, i have a controller bean, this controller might have some default service beans, which can be dependency injected by configuration. while there could also be many additional or new services this controller can invoke now or later, which then need the service locator to retrieve the service beans.

share|improve this answer

Your Answer


