João Pedro Schmitt
João Pedro Schmitt

Reputation: 1498

Inject spring beans into a non-managed class

I have this non-managed class that I want to inject spring beans (that I don't known a-priory what they are). How can I do that?

For example, let's say I have the following class:

public class NonManagedClass extends APIClass {

  @Resource
  private Service1 service;

  @Resource
  private Service2 service2;

  // here i can declare many different dependencies

  @Resource
  private ServiceN serviceN;

  @Override
  public void executeBusinessStuffs() {
    // business logics
  }

}

I need in someway to let spring inject these dependencies in my class. I have access to these objects after created, so it's easy to me call any method that can accomplish this functionality. For example:

@Service
public void SomeAPIService {

  @Resource
  private BeanInjector beanInjector; // I'm looking for some funcionality of spring like this

  public void someProcessingFunction(Class<? extends APIClass> clazz) throws Exception {
    APIClass instance = clazz.getConstructor().newInstance();
    beanInjector.injectBeans(instance);
    instance.executeBusinessStuffs();
  }

}

Does Spring have such functionality to inject beans based on fields annotation for a non-managed class?

Upvotes: 0

Views: 1216

Answers (1)

M. Deinum
M. Deinum

Reputation: 125292

Replace BeanInjector with ApplicationContext and you are almost there. From there you can get the AutowireCapableBeanFactory which provides some handy methods like createBean and autowireBean.

@Service
public void SomeAPIService {

  @Resource
  private ApplicationContext ctx;

  public void someProcessingFunction(Class<? extends APIClass> clazz) throws Exception {
    APIClass instance = ctx.createBean(clazz);
    instance.executeBusinessStuffs();
  }
}

or if you really like to construct stuff yourself instead of using the container:

@Service
public void SomeAPIService {

  @Resource
  private ApplicationContext ctx;

  public void someProcessingFunction(Class<? extends APIClass> clazz) throws Exception {
    APIClass instance = clazz.getConstructor().newInstance();
    ctx.getAutowireCapableBeanFactory().autowireBean(instance);
    instance.executeBusinessStuffs();
  }
}

Upvotes: 3

Related Questions