Mahesh
Mahesh

Reputation: 223

Why would a class ever need access to Spring context?

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?

Upvotes: 4

Views: 190

Answers (2)

axtavt
axtavt

Reputation: 242706

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.

Upvotes: 4

Milad Naseri
Milad Naseri

Reputation: 4118

There are, in fact, many such use cases. Suppose you want to write an authenticator class, which is needed to be accessed by a certain service bean. Now, the authenticator class has been already configured via Spring context. How do you access that bean, then? The answer is via the Spring ApplicationContext:

class MyClass implements ApplicationContextAware {

    private ApplicationContext context;

    @Override
    void setApplicationContext(ApplicationContext context) throws BeansException {
        this.context = context;
    }

    public void execute() {
        Authenticator authenticator = context.getBean("authenticator", Authenticator.class);
        if (!authenticator.authenticate()) {
            //do some stuff
        } else {
            //do some other stuff
        }
   }
}

It is important to note that you wont gain access to the configured beans via any way other than your application context. Also, instantiating another ApplicationContext is not the answer, as it will repeat all the configuration.

Upvotes: 0

Related Questions