Home > Back-end >  How to load manual objects created via reflection into spring context
How to load manual objects created via reflection into spring context

Time:08-09

There are two application. Main Application and Utility Application where utility Application is packaged as jar in Main application. Both are spring boot application. In utility application I create an object of a class A which is present in Main Application using reflection API. Class A has one Autowired instance variable defined in it. Issue is when Utility Application tried to run some method one the same class A object, then that autowired variable results in null. I guess, since I am creating the object manually that is why it is not managed by Spring. Now my question is how can provide this object to spring context so that any Autowiring happening inside the class A actually gets autowired. Below is the code samples

under Main Application 
package m.main.application.A;
class A implements Action{    //Action interface coming from utility application

@Autowired
private Calculator calculator

@override
public void execute(){
    calculator.add(5 2);  //Here calculator is null. Autowire is not working
}
}
Utility Application packaged as Jar in Main Application

Class Util{
   
    public createObjectAndRun(){
      
      Class<?> class = Class.forName("com.main.application.A");
      Action newObject= (Action) class.getConstructor().newInstance();
      
      //executing execute
      newObjects.execute();  //This fails as calculator is not autowired

      
    }
}

I want to know if there is a way we can make calculator gets autowired properly.

CodePudding user response:

Your class A is not annotated with any spring stereotype (@Service, @Component, etc), so it's not a spring managed bean. So one way you could achieve this would be making it a spring bean (using a stereotype) and get it through ApplicationContext's method getBean on your Util class.

  • Related