将springbean注入到非托管类中



我有一个非托管类,我想注入springbean(我不知道它们是什么(。我该怎么做?

例如,假设我有以下类:

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
}
}

我需要以某种方式让spring在我的类中注入这些依赖项。我可以在创建后访问这些对象,所以我很容易调用任何可以实现此功能的方法。例如:

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

Spring是否具有基于非托管类的字段注释注入bean的功能?

BeanInjector替换为ApplicationContext,您就差不多完成了。从那里你可以得到AutowireCapableBeanFactory,它提供了一些方便的方法,比如createBeanautowireBean

@Service
public void SomeAPIService {
@Resource
private ApplicationContext ctx;
public void someProcessingFunction(Class<? extends APIClass> clazz) throws Exception {
APIClass instance = ctx.createBean(clazz);
instance.executeBusinessStuffs();
}
}

或者,如果你真的喜欢自己构建东西,而不是使用容器:

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

最新更新