我有这个非托管类,我想注入spring bean(我不知道它们是什么)。我该怎么办?
例如,假设我有以下课程:
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的功能?
答案 0 :(得分:3)
将BeanInjector
替换为ApplicationContext
,您就快到了。从那里可以获得AutowireCapableBeanFactory
,它提供了一些方便的方法,例如createBean
和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();
}
}
或者如果您真的想自己构造东西而不使用容器:
@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();
}
}