[英]Wiring a spring managed bean from a class which is not managed by spring
Is it possible to wire a Spring Managed Bean into a class which is not managed by Spring IoC? 是否可以将Spring Managed Bean连接到不受Spring IoC管理的类中? Let's say there are two classes
ClassA
(not managed by spring) and ClassB
(managed by Spring) is it possible to wire ClassB
in ClassA
. 假设有两个类
ClassA
(不受spring管理)和ClassB
(受Spring管理),是否有可能在ClassA
ClassB
。
This was a recent question I came across and I had no clue how to do it? 这是我最近遇到的一个问题,我不知道该怎么做?
Yes It is possible. 对的,这是可能的。 You'll need an
ApplicationContextAware
implementation for getting the Spring Managed Bean instance using the ApplicationContext
. 您将需要一个
ApplicationContextAware
实现,以使用ApplicationContext
获取Spring Managed Bean实例。 It's an old Spring Framework trick. 这是一个古老的Spring Framework技巧。
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public final class BeanUtil implements ApplicationContextAware {
private static ApplicationContext CONTEXT;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
CONTEXT = applicationContext;
}
public static <T> T getBean(Class<T> beanClass) {
return CONTEXT.getBean(beanClass);
}
}
Then you must use BeanUtil::getBean
static method in ClassA to get the ClassB instance within the ApplicationContext
. 然后,必须在ClassA中使用
BeanUtil::getBean
静态方法在ApplicationContext
获取ClassB实例。
public class ClassA {
private ClassB classB;
@Override
public String toString() {
return "ClassA - " + getClassB().toString();
}
// Lazy initialization of ClassB to avoid NullPointerException
private ClassB getClassB() {
if (classB == null) {
classB = BeanUtil.getBean(ClassB.class);
}
return classB;
}
}
Forget about "wiring" if Spring is not managing the bean. 如果Spring不管理Bean,请不用担心“接线”。 Instead, just solve the problem of "How do I get a reference to a managed bean into a non-managed bean".
相反,只需解决“如何将对托管Bean的引用转换为非托管Bean”的问题。
In your example, since ClassA
is not managed by Spring you must be creating it somewhere. 在您的示例中,由于
ClassA
不是由Spring管理的,因此您必须在某个地方创建它。 Pass a reference to ClassB
to ClassA
when you create the instance of ClassA
. 传递一个参考
ClassB
到ClassA
当您创建的实例ClassA
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.