Spring获取ApplicationContext的几种方法
相关文章链接:
观前提示:
本文所使用的IDEA版本为ultimate 2019.1,JDK版本为1.8.0_141,Tomcat版本为9.0.12。
本文的例子均在上述链接参考文章搭建的框架。
1.ApplicationContext简介
实用的Bean工厂ApplicationContext。
ApplicationContext的中文意思是“应用前后关系”,它继承自BeanFactory接口,除了包含BeanFactory的所有功能之外,在国际化支持、资源访问(如URL和文件)、事件传播等方面进行了良好的支持,被推荐为Java EE应用之首选,可应用在Java APP与Java Web中。
2.获取方法
2.1 通过Spring提供的工具类WebApplicationContextUtils获取
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext);
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext);
ac1.getBean(Class);
ac2.getBean("beanId");
实例
UserService.java
package com.example.service;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public void insertUser() {
System.out.println("插入用户成功");
}
public boolean updateUser() {
System.out.println("更新用户成功");
return true;
}
}
拦截器RequestMappingInterceptor.java中的部分测试方法
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
UserService u1 = ac1.getBean(UserService.class);
UserService u2 = ac2.getBean(UserService.class);
u1.insertUser();
u2.updateUser();
return super.preHandle(request, response, handler);
}
测试结果
注:这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后在通过它获取需要的类实例。
2.2 初始化时保存ApplicationContext对象
ApplicationContext ac1 = new ClassPathXmlApplicationContext("**/applicationContext.xml");
(Class) ac1.getBean("beanId");
ac1.getBean(Class);
实例
结构如下
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=