Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a method a Spring Bean from a class not in the Spring Container

I'm not a Spring pro, so please bear with me....

I have three classes:

class SpringBeanA {
    public aMethod() {
        .....
    }
}

class SpringBeanB {

    @Autowired SpringBeanA a;

    public bMethod() {
        a.method();
    }
}

class NONSpringClass {
    .....
    b.method();
    .....
}

b.method() gives a null pointer error, both when accesed via the instances SpringBeanB b = new SpringBeanB() and autowiring SpringBeanB to NONSpringClass.

The autowiring:

class NONSpringClass {

    @Autowired SpringBeanB b;

    .....
    b.method();
    .....
}

How can I successfully call b.method()?

like image 649
Program-Me-Rev Avatar asked Jan 18 '15 00:01

Program-Me-Rev


2 Answers

Spring initializes all the objects and keep it in Spring Application Context. You have couple different ways to get access to objects inside Application context

First create a spring configuration class to inject ApplicationContext in to a private attribute and expose as static method.

@Configuration
class StaticApplicationContext implements ApplicationContextAware{

  static ApplicationContext applicationContext = null;

  public void setApplicationContext(ApplicationContext context)    throws BeansException {
    applicationContext = context;
  }
  /**
   * Note that this is a static method which expose ApplicationContext
   **/
  public static ApplicationContext getContext(){
        return applicationContext;
  }

}

Now you can try this in your non spring class,

((SpringBeanB)StaticApplicationContext.getContext.getBean("b")).bMethod();

Please keep in mind, invoking getContext method before spring context initialization may cause NullPointerException. Also accessing beans outside of spring container is not a recommended approach. Ideal way will be to move all beans in to spring container to manage.

If you want to access SpringApplicationContext from a java Servelet please refer WebApplicationContextUtils

like image 162
kamoor Avatar answered Nov 16 '22 04:11

kamoor


A simple way to do this is using ApplicationContext.getBean().

It's worth pointing out that this is considered bad practice, since it breaks inversion of control.

like image 33
Davis Yoshida Avatar answered Nov 16 '22 03:11

Davis Yoshida