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

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

package com.github.bingoohuang.utils.spring;

import lombok.val;
import org.apache.commons.lang3.StringUtils;
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));
    }


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

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

        for (val entry : beansOfType.entrySet()) {
            if (entry.getValue().getClass() == clazz) return entry.getValue();
        }

        throw 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