0

I want to know how to Autowire sprig beans in java object that are not managed by spring application context. I have created an instance of a class and but the subsequent autowiring objects are null. for eg.

@Service
Class BaseFactory {
public BaseObject getObject(String type ){
    BaseObject object = null; 
    if(type.equalsIgnoreCase("order")){
       object = new FirstServiceObject();
    }
   else if(type.equalsIgnoreCase("payment")){
      object = new SecondServiceObject();
    }
  return object;
}

Service class

@Service
@Configurable
public class FirstServiceObject{

@Autowired
UserRepository mUserRepository;// coming as null

@Autowired
UserHelper userHelper;//coming as null

public getDownloadedData(String userName, String b){
   User user = userHelper.findUser(userName); //null pointer exception
}

}

My helper Class from where I am calling the above .

public class SomeHelper {

@Autowired
BaseFactory baseFactory;

public processUser(){
 BaseObject object = baseFactory.getObject("order");
 object.getDownloadedData("sunil","someString")
}

All the Autowired beans a coming as null inside FirstServiceObject

I have checked with all possible solution given already and none seems to be working for me.

Sunil Sharma
  • 163
  • 1
  • 15

3 Answers3

1

Answer given in the following post solved the issue. How to inject dependencies into a self-instantiated object in Spring? This is what I have done

public class SomeHelper {

  @Autowired
  BaseFactory baseFactory;

  @Autowired
  AutowireCapableBeanFactory beanFactory;

  public processUser(){
    BaseObject object = baseFactory.getObject("order");
    beanFactory.autowireBean(object);
    object.getDownloadedData("sunil","someString");
 }
}
Community
  • 1
  • 1
Sunil Sharma
  • 163
  • 1
  • 15
0

You Can't

If you want to Autowired spring beans in your class, the class needs to be managed by Spring.

TheEwook
  • 11,037
  • 6
  • 36
  • 55
0

If you application is using web context, then try this

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
arseniyandru
  • 760
  • 1
  • 7
  • 16