spring 如何取的IOC容器得到里面的对象进行操作

来源:互联网 发布:godaddy 域名证书生成 编辑:程序博客网 时间:2024/06/05 19:04
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();}}

0 0