Accessing Spring managed services from a non-spring managed class
- January 2, 2019
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
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.
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.