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

com.github.yiuman.citrus.support.utils.SpringUtils Maven / Gradle / Ivy

There is a newer version: 0.15.0
Show newest version
package com.github.yiuman.citrus.support.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Spring相关工具
 *
 * @author yiuman
 * @date 2020/4/4
 */
@Component
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext context;

    public SpringUtils() {
    }

    @Override
    public void setApplicationContext(@Nullable ApplicationContext applicationContext) throws BeansException {
        if (context == null) {
            context = applicationContext;
        }
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static  T getBean(Class clazz) {
        return getBean(clazz, false);
    }

    public static  T getBean(Class clazz, boolean force) {
        T bean;
        try {
            bean = context.getBean(clazz);
        } catch (NoSuchBeanDefinitionException ex) {
            bean = force ? context.getAutowireCapableBeanFactory().createBean(clazz) : null;
        }
        return bean;
    }

    public static  T getBean(Class tClass, String name) {
        return context.getBean(name, tClass);
    }

    public static  T getBean(Class clazz, String name, boolean force) {
        T bean;
        try {
            bean = context.getBean(name, clazz);
        } catch (NoSuchBeanDefinitionException ex) {
            bean = force ? context.getAutowireCapableBeanFactory().createBean(clazz) : null;
        }
        return bean;
    }

    public static  Map getBeanOfType(Class type) {
        return context.getBeansOfType(type);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy