从不是由spring管理的类连接spring管理的bean
是否可以将一个Spring管理的Bean连接到一个不可用的类中 由春季国际奥委会管理? 假设有两个类从不是由spring管理的类连接spring管理的bean,spring,Spring,是否可以将一个Spring管理的Bean连接到一个不可用的类中 由春季国际奥委会管理? 假设有两个类ClassA(不由spring管理)和 ClassB(由Spring管理)是否可以在ClassA中连接ClassB 这是我最近遇到的一个问题,我不知道怎么做?是的,这是可能的。您需要一个ApplicationContextAware实现来使用ApplicationContext获取Spring托管Bean实例。这是一个古老的Spring框架技巧 import org.springframework
ClassA
(不由spring管理)和
ClassB
(由Spring管理)是否可以在ClassA
中连接ClassB
这是我最近遇到的一个问题,我不知道怎么做?是的,这是可能的。您需要一个
ApplicationContextAware
实现来使用ApplicationContext
获取Spring托管Bean实例。这是一个古老的Spring框架技巧
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);
}
}
是的,这是可能的。您需要一个
ApplicationContextAware
实现来使用ApplicationContext
获取Spring托管Bean实例。这是一个古老的Spring框架技巧
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);
}
}
如果Spring没有管理bean,那么就不要考虑“连接”。
相反
只需解决“如何将对托管bean的引用转换为非托管bean”的问题
以你为例,,
因为ClassA
不是由Spring管理的,所以您必须在某处创建它。
创建ClassA
的实例时,将对ClassB
的引用传递给ClassA
,如果Spring没有管理bean,请忘记“连接”。
相反
只需解决“如何将对托管bean的引用转换为非托管bean”的问题
以你为例,,
因为ClassA
不是由Spring管理的,所以您必须在某处创建它。
创建ClassA
实例时,将对ClassB
的引用传递给ClassA