| | |
| | | import org.springframework.context.ApplicationContextAware; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | /** |
| | | * Spring上下文帮助类 |
| | | * @author WWW |
| | | */ |
| | | @Component |
| | | @SuppressWarnings("ALL") |
| | | public class SpringContextHelper implements ApplicationContextAware { |
| | | private static ApplicationContext context = null; |
| | | |
| | | /** |
| | | * 设置应用程序上下文 |
| | | * |
| | | * @param applicationContext |
| | | * @throws BeansException |
| | | */ |
| | | @Override |
| | | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { |
| | | context = applicationContext; |
| | | } |
| | | |
| | | /** |
| | | * 根据名称获取Bean |
| | | * |
| | | * @param name 类名称 |
| | | * @return |
| | | */ |
| | | public static <T> T getBean(String name) { |
| | | return (T) context.getBean(name); |
| | | } |
| | | |
| | | /** |
| | | * 根据类型获取Bean |
| | | * |
| | | * @param clazz 类 |
| | | * @param <T> 泛型 |
| | | * @return |
| | | */ |
| | | public static <T> T getBean(Class<T> clazz) { |
| | | return context.getBean(clazz); |
| | | } |
| | | |
| | | /** |
| | | * 判断是否包含对应名称的Bean对象 |
| | | * |
| | | * @param name Bean名称 |
| | | * @return 包含:返回true,否则返回false。 |
| | | */ |
| | | public static boolean containsBean(String name) { |
| | | return context.containsBean(name); |
| | | } |
| | | |
| | | /** |
| | | * 获取对应Bean名称的类型 |
| | | * |
| | | * @param name Bean名称 |
| | | * @return 返回对应的Bean类型 |
| | | */ |
| | | public static Class<?> getType(String name) { |
| | | return context.getType(name); |
| | | } |
| | | |
| | | /** |
| | | * 获取上下文对象,可进行各种Spring的上下文操作 |
| | | * |
| | | * @return Spring上下文对象 |
| | | */ |
| | | public static ApplicationContext getContext() { |
| | | return context; |
| | | } |
| | | |
| | | |
| | | /** |
| | | * 获取当前环境 |
| | | * |
| | | * @return Profile |
| | | */ |
| | | public static String getActiveProfile() { |
| | | return context.getEnvironment().getActiveProfiles()[0]; |
| | | } |