How to Get Spring Managed Service Instance Outside the Action Class in Struts2

In Struts 2, we can configure Spring to inject service instanced using Dependency Injection into Action classes. But sometime we need these service class instances in other components who are are Spring aware. For example you need AccountsService instance in StudentService class. For such purpose I have createds util class which can return me reference to any service instance at run time, in any class.

I call is SpringContext, here is its definition:
package com.bitspedia.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContext implements ApplicationContextAware {

private static ApplicationContext CONTEXT;

public void setApplicationContext(ApplicationContext context) throws BeansException {
CONTEXT = context;
}
public static Object getBean(String beanName) {
return CONTEXT.getBean(beanName);
}
}
Now getting the reference to any Spring managed service is very easy, in any service class or somewhere else:
AccountsService accService = (AccountsService)SpringContext.getBean("accountsService");
I assume you have already defined the accountService and studentService bean in applicationContext.xml.

Comments