Reputation: 401
Is it possible to wire a Spring Managed Bean into a class which is not
managed by 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
.
This was a recent question I came across and I had no clue how to do it?
Upvotes: 0
Views: 62
Reputation: 38348
Forget about "wiring" if Spring is not managing the bean. Instead, just solve the problem of "How do I get a reference to a managed bean into a non-managed bean".
In your example,
since ClassA
is not managed by Spring you must be creating it somewhere.
Pass a reference to ClassB
to ClassA
when you create the instance of ClassA
.
Upvotes: 1
Reputation: 3262
Yes It is possible. You'll need an ApplicationContextAware
implementation for getting the Spring Managed Bean instance using the ApplicationContext
. It's an old Spring Framework trick.
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
.
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;
}
}
Upvotes: 1