All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.kasinf.framework.rest.web.util.SpringUtils Maven / Gradle / Ivy

There is a newer version: 1.4.0
Show newest version
package com.kasinf.framework.rest.web.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import java.lang.annotation.Annotation;

/**
 * @author 凯鸿.
 * 普通类调用Spring bean对象:
 */
public final class SpringUtils {

    private static ConfigurableListableBeanFactory beanFactory;

    public SpringUtils(ConfigurableListableBeanFactory beanFactory) {
        SpringUtils.beanFactory = beanFactory;
    }

    /**
     * 获取对象
     *
     * @return Object 一个以所给名字注册的bean的实例
     */
    @SuppressWarnings("unchecked")
    public static  T getBean(String name) throws BeansException {
        return (T) beanFactory.getBean(name);
    }

    /**
     * 返回所有继承了某一接口的bean
     *
     * @param clazz:某一接口
     * @return 所有类名
     */
    public static String[] getBeanForType(Class clazz) {
        return beanFactory.getBeanNamesForType(clazz);
    }

    /**
     * 返回所有有某一注解的类
     *
     * @param clazz 某一注解
     * @return 所有类名
     */
    public static String[] getBeanForAnnotation(Class clazz) {
        return beanFactory.getBeanNamesForAnnotation(clazz);
    }

    /**
     * 获取类型为requiredType的对象
     *
     * @param clz 指定类
     */
    public static  T getBean(Class clz) throws BeansException {
        return beanFactory.getBean(clz);
    }

    /**
     * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
     *
     * @return boolean
     */
    public static boolean containsBean(String name) {
        return beanFactory.containsBean(name);
    }

    /**
     * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
     *
     * @return boolean
     */
    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
        return beanFactory.isSingleton(name);
    }

    /**
     * @return Class 注册对象的类型
     */
    public static Class getType(String name) throws NoSuchBeanDefinitionException {
        return beanFactory.getType(name);
    }

    /**
     * 如果给定的bean名字在bean定义中有别名,则返回这些别名
     */
    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
        return beanFactory.getAliases(name);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy