spring 如何取的IOC容器得到里面的对象进行操作
2015-08-31 11:04
489 查看
import java.util.HashMap; import java.util.Map; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * spring工具类 * * */ public class SpringUtil { private static ApplicationContext applicationContext=null; public static final String SCOPE_REQUEST = "requestContextHolder"; public static final String SCOPE_SESSION = "sessionContextHolder"; public static final String SCOPE_APPLICATION = "applicationContextHolder"; @SuppressWarnings("rawtypes") private static Map contexts = new HashMap(); @SuppressWarnings("static-access") public Object get(String key) { return this.contexts.get(key); } @SuppressWarnings({ "unchecked", "static-access" }) public void put(String key, Object value) { this.contexts.put(key, value); } @SuppressWarnings("static-access") public void clear() { this.contexts.clear(); } public static ApplicationContext getApplicationContext() { if (applicationContext == null) { applicationContext = new ClassPathXmlApplicationContext("classpath:mvc-config.xml","classpath:beans-config.xml");//配置文件路径 setApplicationContext(applicationContext); } return applicationContext; } public static void setApplicationContext(ApplicationContext context) { applicationContext = context; } /** * 根据beanId取得实例 * * @param <T> * @param beanId * @return */ @SuppressWarnings("unchecked") public static <T> T getBean(String beanId) { return (T) getApplicationContext().getBean(beanId); } @SuppressWarnings("unchecked") public static void put(String key, Object value, String scopeBeanId) { contexts = getBean(scopeBeanId); if (contexts != null) contexts.put(key, value); } @SuppressWarnings("unchecked") public static <T> T get(String key, String scopeBeanId) { contexts = getBean(scopeBeanId); if (contexts != null) return (T) contexts.get(key); return null; } public static void clear(String scopeBeanId) { contexts = getBean(scopeBeanId); if (contexts != null) contexts.clear(); } }
相关文章推荐
- MyEclipse使用总结——MyEclipse10安装SVN插件
- SpringMVC
- java并发:Timer的缺陷 用ScheduledExecutorService替代 .
- Java数组练习冒泡排序
- java - (08) javaEE
- Java常用的设计模式02:常用设计模式之工厂模式(创建型模式)
- 浅谈Java中的hashcode方法
- 今天线上系统碰到个怪问题DBCP数据连接异常,java.sql.SQLException: Already closed.
- 修改eclipse中web项目的server部署路径
- java数组练习2创建二维数组,并将数组中的内容输出到控制台
- 短信猫 Java
- java并发:ExecutorServiec中的CompletionService和invokeAll的使用
- Spring.NET程序
- Genymotion中SD卡目录在Eclipse中查看,以及创建SDCard
- java基础I/O系列--FileInputStream 和 FileOutputStream 介绍
- 【java】访问修饰符
- Java位运算
- 【spring框架】(二)控制反转(IOC)容器
- eclipse中类结构中各个小图标的含义
- JAVA基础10--行为型模式(责任链模式 迭代器模式 中介者模式 命令模式 策略模式)