参考 : https://ask.youkuaiyun.com/questions/947552
场景 : 在未由Spring管理的类中获取由Spring管理的类实例,发现直接new之后,该实例中的所有注入都是空的,网上搜索之后找到该方案
1.Service注解设定bean名称
@Service("testService")
2.根据bean名称获取由Spring管理的类实例
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext context;
public void setApplicationContext(ApplicationContext context)
throws BeansException {
this.context = context;
}
public static ApplicationContext getContext() {
return context;
}
}
3.在未由Spring管理的类中获取由Spring管理的类,其中的两种方式
TestService tesrService = (TestService)ApplicationContextUtil.getContext().getBean("tesrService ");
TestService tesrService = (TestService)ApplicationContextUtil.getContext().getBean(TestService .class);
END。
本文介绍如何在未被Spring管理的类中正确获取并使用由Spring管理的Bean实例。通过@Service注解设置bean名称,利用ApplicationContextAware接口及其实现类ApplicationContextUtil,可在任意类中通过静态方法获取到Spring上下文,进而获取到所需的Bean实例。
174万+

被折叠的 条评论
为什么被折叠?



