- 1@Component 2 public final class SpringHandle implements BeanFactoryPostProcessor {
- 3 4 private static ConfigurableListableBeanFactory beanFactory; // Spring应用上下文环境
- 5 6 public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
- 7 SpringHandle.beanFactory = beanFactory;
- 8
- }
- 9 10
- /**
- 11 * 获取对象
- 12 *
- 13 * @param name
- 14 * @return Object 一个以所给名字注册的bean的实例
- 15 * @throws org.springframework.beans.BeansException
- 16 *
- 17 */
- 18@SuppressWarnings("unchecked") 19 public static T getBean(String name) throws BeansException {
- 20
- return (T) beanFactory.getBean(name);
- 21
- }
- 22 23
- /**
- 24 * 获取类型为requiredType的对象
- 25 *
- 26 * @param clz
- 27 * @return
- 28 * @throws org.springframework.beans.BeansException
- 29 *
- 30 */
- 31 public static T getBean(Class clz) throws BeansException {
- 32 T result = (T) beanFactory.getBean(clz);
- 33
- return result;
- 34
- }
- 35 36
- /**
- 37 * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
- 38 *
- 39 * @param name
- 40 * @return boolean
- 41 */
- 42 public static boolean containsBean(String name) {
- 43
- return beanFactory.containsBean(name);
- 44
- }
- 45 46
- /**
- 47 * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
- 48 * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
- 49 *
- 50 * @param name
- 51 * @return boolean
- 52 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
- 53 *
- 54 */
- 55 public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
- 56
- return beanFactory.isSingleton(name);
- 57
- }
- 58 59
- /**
- 60 * @param name
- 61 * @return Class 注册对象的类型
- 62 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
- 63 *
- 64 */
- 65 public static Class getType(String name) throws NoSuchBeanDefinitionException {
- 66
- return beanFactory.getType(name);
- 67
- }
- 68 69
- /**
- 70 * 如果给定的bean名字在bean定义中有别名,则返回这些别名
- 71 *
- 72 * @param name
- 73 * @return
- 74 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
- 75 *
- 76 */
- 77 public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
- 78
- return beanFactory.getAliases(name);
- 79
- }
- 80 81
- }
来源: http://www.cnblogs.com/iceworld520/p/7066388.html