Search code examples
javaspringapplicationcontext

Alternative for ApplicationContext aware


I am in a situation where i have a class (badly designed) with only static methods and Im adding a new field within it which will be initialized to a bean managed by spring. This field will be used by one of the static methods.

I found that I can create a new class which will be context aware and get the bean from that class.

class A implements ApplicationContextAware{

   static beanType givebean(){
   }

   //Code to retrieve bean from application context    
}

class B{

  static beanType bean;

  static void method1(){
      bean = A.giveBean();
      //does stuffs
  }

  static void method2(){
  }

}


 configuration file::
  <bean id="bean" class="X.X.X.X.beanType"/>

My question is other than using Applicationcontextaware is there a way to use a bean within a class not managed by spring. I am not against using Appcontextaware but i am wondering if these are other possibilities to do this.Thanks.


Solution

  • If you are in a web application you can use:

    Then:

    WebApplicationContextUtils.getApplicationContext(extract servlet context from request for example)).getBean("beanid")
    

    Regards