package com.changhong.autoform.core.spring;
|
|
import java.util.ArrayList;
|
import java.util.List;
|
import java.util.Map;
|
|
import org.springframework.beans.BeansException;
|
import org.springframework.context.ApplicationContext;
|
import org.springframework.context.ApplicationContextAware;
|
import org.springframework.stereotype.Service;
|
|
import com.changhong.autoform.core.exception.AutoFormException;
|
|
/**
|
* 获得spring管理的bean
|
* @ClassName: SpringContext
|
* @author [九鼎联合科技]
|
* @date 2017年6月2日 上午10:42:38
|
*/
|
@Service
|
public class SpringContext implements ApplicationContextAware{
|
|
/*
|
* spring上下文
|
*/
|
private static ApplicationContext applicationContext;
|
/**
|
* 获得spring容器上下文
|
* @Title: getApplicationContext
|
* @param @return 设定文件
|
* @return WebApplicationContext 返回类型
|
* @throws
|
*/
|
public static ApplicationContext getApplicationContext(){
|
return applicationContext;
|
}
|
|
/**
|
* 获得spring容器管理的bean
|
* @Title: getBean
|
* @param @param name
|
* @param @return 设定文件
|
* @return Object 返回类型
|
* @throws
|
*/
|
public static Object getBean(String name){
|
return getApplicationContext().getBean(name);
|
}
|
|
/**
|
* 获得spring容器管理的bean
|
* @Title: getBean
|
* @param @param clazz
|
* @param @return 设定文件
|
* @return T 返回类型
|
* @throws
|
*/
|
public static <T> T getBean(Class<T> clazz, BeanFilter bf){
|
Map<String, T> beans = getApplicationContext().getBeansOfType(clazz);
|
if(beans.size() == 1){
|
return new ArrayList<>(beans.values()).get(0);
|
}else if(beans.size() > 1){
|
for(Map.Entry<String, T> entry : beans.entrySet()){
|
if(bf != null){
|
if(bf.filter(entry.getKey())){
|
return entry.getValue();
|
}
|
}
|
}
|
throw new AutoFormException(String.format("没有'%s'类型的bean", clazz.getName()));
|
}else{
|
throw new AutoFormException(String.format("没有'%s'类型的bean", clazz.getName()));
|
}
|
}
|
|
/**
|
* 获得bean
|
* @param clazz
|
* @return
|
*/
|
public static <T> T getBean(Class<T> clazz){
|
Map<String, T> beans = getApplicationContext().getBeansOfType(clazz);
|
if(beans == null || beans.isEmpty()){
|
return null;
|
}
|
return new ArrayList<>(beans.values()).get(0);
|
}
|
|
/**
|
* 获得bean集合
|
* @param clazz
|
* @return
|
*/
|
public static <T> List<T> getBeans(Class<T> clazz){
|
return new ArrayList<>(getApplicationContext().getBeansOfType(clazz).values());
|
}
|
|
/**
|
* 获得spring容器管理的bean
|
* @Title: getBean
|
* @param @param name
|
* @param @param clazz
|
* @param @return 设定文件
|
* @return T 返回类型
|
* @throws
|
*/
|
@SuppressWarnings("unchecked")
|
public static <T> T getBean(String name, Class<T> clazz){
|
return (T) getApplicationContext().getBean(name);
|
}
|
|
@Override
|
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
SpringContext.applicationContext = applicationContext;
|
}
|
|
}
|