Why would a class ever need access to Spring context?

dependency-injection, java, spring

Solution

Usually beans don't need to access `ApplicationContext` directly.

However, there are cases when direct access is necessary. For example:

To access a bean identified by its name at runtime:

class MyClass implements ApplicationContextAware {
    ...
    public void execute(String actionName) {
        Action action = applicationContext.getBean(actionName);
        action.execute();
    }
    ...
}

To pass custom arguments to constuctor of `prototype`-scoped bean at runtime:

Bean bean = applicationContext.getBean("myBean", "foo", "bar");

Note that if `Bean`'s constructor doesn't need custom arguments to be passed at runtime, you can inject `ObjectFactory<Bean>` instead.

To trigger autowiring of third-party objects using `AutowireCapableBeanFactory`.

Problem

I see that it is possible for both Spring beans and other regular classes to access the spring application context. I'm wondering why would a class ever have to deal with Spring context. My understanding is that, in the main method, you bootstrap your application and everything from that point is wired by Spring. If that is the case, main method should be the only place where you need ApplicationContext. What are the other genuine cases where you need Spring context to get your work done?

Original source