开发过程当中部分bean并不是交给spring来管理,可是这部分bean中又使用到了spring管理的bean,且生命周期还须要与spring管理的bean一致.因此就找到了如下方法.java
package com.weixin.common.util; import java.util.HashMap; import java.util.Map; import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoader; /** * SpringContext手动工具 * 此类只能够在单例web项目中使用,若是该web项目有作集群,请采用其余方法获取. * @author fong * @date 2016-11-10 上午10:56:04 */ public class SpringContextUtil { private static ApplicationContext context; private SpringContextUtil() { } private static ApplicationContext getContext() { if (context == null) { synchronized (SpringContextUtil.class) { if (context == null) { context = ContextLoader.getCurrentWebApplicationContext(); } } } return context; } /** * 从当前web实例的Application中获取bean * @param clazz * @return */ public static <T> T getBean(Class<T> clazz) { return getContext().getBean(clazz); } /** * 获取当前web实例的ApplicatinContext * @return */ public static ApplicationContext getApplicationContext() { return getContext(); } }
说明:web
在网上还有其余几种方式能够获取springContext,可是下面这几种要么是从新加载了一个spring容器要么就是必需要容器使用的类被容器初始化.spring
1. 直接加载文件获取 (这是一个新的容器,与当前web实例获得的bean是不同的,能够用单例作测试)app
ApplicationContext context = new FileSystemXmlApplicationContext("xxx.xml"); ApplicationContext context = new ClassPathXmlApplicationContext("resource/spring-beans.xml");
2.继承抽象类或者实现接口(注意必须由Spring初始化SpringContextUtil,不然获得的会是NULL)工具
// 继承ApplicationObjectSupport或者WebApplicationObjectSupport public class SpringContextUtil extends ApplicationObjectSupport{ // 直接用就能够了 public SpringContextUtil() { // 父类已经定义了 getApplicationContext/setApplicationContext, // 并且是final的方法 super.getApplicationContext(); } } // 接口 public class SpringContextUtil implements ApplicationContextAware{ private ApplicationContext applicationContext; public void setApplicationContext(ApplicationContext applicationContext)throws BeansException { this.applicationContext = applicationContext; } public ApplicationContext getApplicationContext(){ return this.applicationContext; } }
3.经过Spring提供的工具直接获取(须要在Controller层来作)测试
@Controller @RequestMapping("/test") public class Test { @RequestMapping(value = "/hello") public @ResponseBody String helloPost(HttpServletRequest req) { ServletContext sc = req.getServletContext(); WebApplicationContextUtils.getRequiredWebApplicationContext(sc) } }