您的位置:首页 > 编程语言 > Java开发

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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: