简体   繁体   中英

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

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

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 .

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