需要在spring配置文件中配置springContextUtil的bean
<bean id="SpringContextUtil" lazy-init="false" class="com.alphajuns.ssm.util.SpringContextUtil" />
SpringContextUtil.java
package com.alphajuns.ssm.util; import org.springframework.beans.BeansException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Repository; @Repository("springContextUtil") public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 按名称获取bean对象 * @param name * @return * @throws BeansException */ public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); } /** * 按名称获取指定类型的bean * @param name * @param requiredType * @return * @throws BeansException */ public static Object getBean(String name, Class requiredType) throws BeansException { return applicationContext.getBean(name, requiredType); } /** * 判断是否包含对应名称的bean * @param name * @return */ public static boolean containsBean(String name) { return applicationContext.containsBean(name); } /** * 获取指定名称bean的类型 * @param name * @return * @throws NoSuchBeanDefinitionException */ public static Class getType(String name) throws NoSuchBeanDefinitionException { return applicationContext.getType(name); } public static String[] getAliases(String name) throws NoSuchBeanDefinitionException { return applicationContext.getAliases(name); } /** * 判断bean为单例模式 * @param name * @return * @throws NoSuchBeanDefinitionException */ public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException { return applicationContext.isSingleton(name); } }
测试
package com.alphajuns.junit; import com.alphajuns.ssm.service.ItemService; import com.alphajuns.ssm.util.SpringContextUtil; import org.junit.Test; import java.util.List; import java.util.Map; public class SpringContextUtilTest extends SuperJunitTest { @Test public void getBean() { ItemService itemService = (ItemService) SpringContextUtil.getBean("itemServiceImpl"); List<Map<String, Object>> itemList = itemService.getItemList(); System.out.println(itemList); } @Test public void isSingleton() { boolean flag = SpringContextUtil.isSingleton("itemServiceImpl"); System.out.println(flag); } }