SpringApplicationContext
是Spring
的一个容器,在Spring
初始化的过程中,SpringApplicationContext
也被初始化了。拿到SpringApplicationContext
后,我们能手动获取bean。我们可以通过一下方法获取
SpringApplicationContext。
-
`拿到配置文件获取上下文,
private LsjmUserServiceImpl user = null; @Before public void getBefore(){ // 这里由于我的配置文件写的目录不是根目录,所以用FileSystemXmlApplicationContext String xmlPath = "WebContent/WEB-INF/config/base/applicationContext.xml"; ApplicationContext ac = new FileSystemXmlApplicationContext(xmlPath); user = ac.getBean(LsjmUserServiceImpl.class); } // 如果是放在根目录下 public void getBefore(){ ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); user = ac.getBean(LsjmUserServiceImpl.class);
-
也可以通过
Spring
的工具类WebApplicationContextUtils
获取。// Spring中获取ServletContext对象,普通类中可以这样获取 ServletContext sc = ContextLoader.getCurrentWebApplicationContext().getServletContext(); // servlet中可以这样获取,方法比较多 ServletContext sc = request.getServletContext(): ServletContext sc = servletConfig.getServletContext(); //servletConfig可以在servlet的init(ServletConfig config)方法中获取得到 /* 需要传入一个参数ServletContext对象, 获取方法在上面 */ // 这种方法 获取失败时抛出异常 ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); // 这种方法 获取失败时返回null ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
-
实现
ApplicationContextAware
接口import java.util.Map; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringContextUtil implements ApplicationContextAware { // Spring应用上下文环境 @Autowired private static ApplicationContext applicationContext; /** * 实现ApplicationContextAware接口的回调方法。设置上下文环境 * * @param applicationContext */ public void setApplicationContext(ApplicationContext applicationContext) { SpringContextUtil.applicationContext = applicationContext; } /** * @return ApplicationContext */ public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 根据名称获取对象 * @param name * @return * @throws BeansException */ public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); } /** * 根据类型获取对象 * @param clazz * @return */ public static <T> T getBean(Class<T> clazz){ return applicationContext.getBean(clazz); } /** * 获取对象 * @param clazz * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static Map<String,Object> getBeansByType(Class clazz){ return applicationContext.getBeansOfType(clazz); } /** * 获取当前项目运行环境 * @return */ public static String getRuntimeEnvironment(){ return applicationContext.getEnvironment().getActiveProfiles()[0]; } }
推荐使用第三种方式。写junit
测试用例使用而且只能使用方法1
网友评论