代码实现:
package com.ht.util; import java.util.Map; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext arg0) throws BeansException { applicationContext = arg0; System.out.println("applicationContext配置文件加载成功!!!!"); } /** * @Title: getApplicationContext * @Description: 获取应用上下文环境 * @return */ public static ApplicationContext getApplicationContext() { checkApplicationContext(); return applicationContext; } /** * @Title: getBean * @Description: 根据bean对象的名字获取bean * @param name * @return */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { checkApplicationContext(); return (T) applicationContext.getBean(name); } /** * @Title: getBean * @Description: 用反射的方法获取bean,如果有多个符合条件的,则返回第一个 * @param clzz * @return 返回类型 */ public static <T> T getBean(Class<T> clzz) { checkApplicationContext(); Map<String, T> mapBeans = applicationContext.getBeansOfType(clzz); if (mapBeans != null && !mapBeans.isEmpty()) { return (T) mapBeans.values().iterator().next(); } else { return null; } } /** * @Title: checkApplicationContext * @Description: 检查applicationContext是否初始化 * @return 返回类型 */ public static void checkApplicationContext() { if (applicationContext == null) { throw new IllegalStateException("applicationContext.xml文件没有加载或者SpringContextUtil没有在applicationContext.xml中注入!!!!!"); } } }
注:
- 该工具类必须实现接口ApplicationContextAware,该接口中有一个方法:void setApplicationContext(ApplicationContext applicationContext),
- 该util必须要在sping的ioc容器中注册,否者在加载applicationContext.xml时,该util的applicationContext不会被初始化
- 通过SpringContextUtil.getBean()可以获取ioc容器中任何一个bean对象。
测试代码:
package com.shareboxes.test; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.shareboxes.model.Student; import com.shareboxes.util.springUtil; public class testSpringUtil { @BeforeClass public static void load(){ @SuppressWarnings("unused") ApplicationContext aContext=new ClassPathXmlApplicationContext(new String[]{"mvcContext.xml"}); } @Test public void testUtil(){ Student student=springUtil.getBean("student");//用spring工具类获取Student对象 System.out.println(student); } }
时间: 2024-10-07 05:45:23