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

com.github.bingoohuang.utils.spring.SpringContext Maven / Gradle / Ivy

The newest version!
package com.github.bingoohuang.utils.spring;

import org.apache.commons.lang3.StringUtils;
import org.jooq.lambda.Seq;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

public abstract class SpringContext implements ApplicationContextAware {
    private static ApplicationContext appContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContext.appContext = applicationContext;
    }

    public static ApplicationContext getAppContext() {
        return appContext;
    }

    @SuppressWarnings("unchecked")
    public static  T getBean(String beanName) {
        return (T) appContext.getBean(StringUtils.uncapitalize(beanName));
    }

    @SuppressWarnings("unchecked")
    public static  T getBeanOrNull(String beanName) {
        if (appContext == null) return null;
        if (StringUtils.isEmpty(beanName)) return null;

        try {
            return (T) appContext.getBean(beanName);
        } catch (NoSuchBeanDefinitionException e) {
            // ignore
        }

        return null;
    }


    public static  T getBean(Class clazz) {
        return appContext.getBean(clazz);
    }

    public static  T getBeanOrNull(Class clazz) {
        if (appContext == null) return null;

        try {
            return appContext.getBean(clazz);
        } catch (NoSuchBeanDefinitionException e) {
            // ignore
        }

        return null;
    }

    public static  T getBeanExactly(Class clazz) {
        Map beansOfType = appContext.getBeansOfType(clazz);
        if (beansOfType.size() == 1) {
            return beansOfType.entrySet().iterator().next().getValue();
        }

        return Seq.seq(beansOfType)
                .filter(x -> x.v2.getClass() == clazz)
                .findFirst()
                .map(x -> x.v2)
                .orElseThrow(() -> new RuntimeException("unable to find bean exactly for " + clazz));
    }

    public static  T inject(T bean) {
        appContext.getAutowireCapableBeanFactory().autowireBean(bean);
        return bean;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy