Accessing Spring managed services from a non-spring managed class

Spring framework is modular framework with many modules for various jobs and spring core is the main module on to which other modules in the system works.

One of the main advantages of using Spring framework is it provides as a solution for your dependency injection requirements, basically when you need to wire up your various services. But there are cases where you need to access Spring managed beans and services from a non-Spring managed context. For example think of a typical message processing listener, basically, this listener might be listening for a topic and processes the messages posted into this topic.

But when processing those messages you might want to use one of Spring-managed service as well. To understand further this service can be a spring managed service having the @service annotation. And it can have an auto-wired DataSource also. So that we do not need to write up all the boilerplate code to set up a Data source. So the challenge is to use this Service class from the non-Spring managed MessageListener class.


A solution for this kind of scenarios is a simple one, we just have to implement ApplicationContextAware interface from Spring’s org.springframework.context package.

It provides a method called

public void setApplicationContext(ApplicationContext context) throws BeansException{
 
}

Then we have to implement this method and keep a static reference for the ApplicationContext in the class that we implemented above. So we could use this context refers to load our required services and beans.

@Component
public class ApplicationSpringContext implements ApplicationContextAware {
 
    private static ApplicationContext context;
 
    public static MessagingService getMessagingService () {
        return (MessagingService ) context.getBean("messageService");
    }
 
 
    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException {
        ApplicationSpringContext.context = context;
    }
}

Here the MessagingService is the service class we need to use from the MessageListener. So we could use the static method getMessagingService() from the above class and use it without any issue. So now we are using a Spring-managed service class from a non-Spring context.