Monday, June 24, 2013

Application Context helper

With Spring taking over the j2ee world, we often end up in situations where we need spring managed beans in static classes or non spring managed beans. Sometimes it could just be decoupling or simplicity, as in u might not want your framework user to take the pain of injecting a utility bean into all beans.
Here is a simple trick I use to solve this


public class ApplicationContextHelper implements ApplicationContextAware{

       private static ApplicationContext context;


       @Override
       public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
               context = applicationContext;
       }

       public static Object getBean(String name,Class clazz){
               return context.getBean(name, clazz);
       }

       public static Object getBean(String name){
               return context.getBean(name);
       }

       public static Object getBean(Class clazz){
               return context.getBean(clazz);
       }

}

and in applicationContext,xml you have.
<bean id="applicationContextHelper" class="com.util.ApplicationContextHelper"/>

Once this is done, you can get any spring managed bean anywhere by using below code

ManagedObject obj = (ManagedObject)ApplicationContextHelper.getBean("objectId");







No comments:

Post a Comment