SpringBoot获取上下⽂,获取bean的⼏种中⽅式
传统Spring项⽬
在写传统的spring项⽬中,⼀般通过初始化抽象类AbstractXmlApplicationContext 的实现类,并传⼊l,来获取应⽤上下⽂,最终通过getBean⽅法获取bean,如下:
ApplicationContext app1 = new FileSystemXmlApplicationContext("l");
ApplicationContext app2 = new ClassPathXmlApplicationContext("l");
SpringBoot项⽬获取bean的⼏种⽅式
1. 通过启动类中返回的上下⽂获取
ConfigurableApplicationContext app = SpringApplication.run(BeanDemoApplication.class, args);
SpringUtil.setAppContext(app);
public class SpringUtil {
private static ApplicationContext appContext;
public static void setAppContext(ApplicationContext appContext) {
SpringUtil.appContext = appContext;
}
public static ApplicationContext getAppContext() {
return appContext;
}
}
在第三⽅类中使⽤:
ApplicationContext appContext = AppContext();
2. 通过⼯具类获取
RequestContextUtils.findWebApplicationContext(HttpServletRequest request),WebApplicationContext(ServletContext sc)
a. 在controller中传⼊request,例如:
springboot原理图解public String test(HttpServletRequest request,HttpServletRequest response) {
WebApplicationContext wc = RequestContextUtils.findWebApplicationContext(request);
WebApplicationContext wc2 = ServletContext());
}
b. 在service中或者其他后端服务中获取:
HttpServletRequest request = ((RequestAttributes()).getRequest();
WebApplicationContext wc = RequestContextUtils.findWebApplicationContext(request);
WebApplicationContext wc2 = ServletContext());
3. 通过实现接⼝ApplicationContextAware
@Component
public class TestApplicationContextAware implements ApplicationContextAware {
private  ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public Object getBean(String beanName) {
Bean(beanName);
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
}
在其他类中调⽤
@Autowired
private TestApplicationContextAware app;
public void testMethod() {
}
4. 通过继承抽象类:ApplicationObjectSupport,WebApplicationObjectSupport 原理参考第3点
5. 其他⽅式
在⽹上看,发现也可以直接调⽤:CurrentWebApplicationContext(),或者CurrentWebApplicationContext() 其实都是调⽤同⼀段代码,如下:
@Nullable
public static WebApplicationContext getCurrentWebApplicationContext() {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl != null) {
WebApplicationContext ccpt = (ccl);
if (ccpt != null) {
return ccpt;
}
}
return currentContext;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。