简体   繁体   中英

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?

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();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM