- 通过加载配置文件方式获取
//不是根目录下
ApplicationContext context = new FileSystemXmlApplicationContext("WebContent/WEB-INF/config/base/applicationContext.xml");
//根目录下
ApplicationContext context1 = new ClassPathXmlApplicationContext("applicationContext.xml");
- 通过 WebApplicationContextUtils 的 getWebApplicationContext(servletContext) 获取,
使用该方法的必须依赖Servlet容器。
public JsonResult edit(SysRoleEntity entity, HttpServletRequest request){
ServletContext servletContext = request.getSession().getServletContext();
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
SysRoleService bean = context.getBean(SysRoleService.class);
boolean modify = sysRoleService.modify(entity);
return new JsonResult().ok(modify);
}
- 通过实现 ApplicationContextAware 接口的方式
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringUtil.context == null){
SpringUtil.context = applicationContext;
}
}
/**
* 获取ApplicationContext
* @return
*/
public static ApplicationContext getContext() {
return context;
}
public static Object getBean(String name){
return getContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz){
return getContext().getBean(clazz);
}
}
重写 setApplicationContext(ApplicationContext applicationContext) 在 String 启动的时候 Spring 会帮我们装载
需要注意的是要把 SpringUtil 交给 Spring 管理 加个 @Component 注解 或者配置