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

org.kaizen4j.common.spring.ApplicationContextHolder Maven / Gradle / Ivy

package org.kaizen4j.common.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import static java.util.Objects.isNull;

/**
 * Spring ApplicationContext 持有类,必须在 Spring 配置文件中进行初始化。
 */
public final class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext webApplicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        webApplicationContext = applicationContext;
    }

    /**
     * 获取 Spring ApplicationContext 对象。
     *
     * @return Spring ApplicationContext
     *
     * @throws IllegalStateException
     */
    public static ApplicationContext getApplicationContext() {
        checkApplicationContextNotNull();
        return webApplicationContext;
    }

    /**
     * 查找 Spring 容器中的 Bean 对象并返回。
     *
     * @param name Spring Bean 定义的唯一标识名
     * @return Spring 容器定义的 Bean 对象
     *
     * @throws IllegalStateException
     */
    @SuppressWarnings(value = "unchecked")
    public static  T getBean(String name) {
        checkApplicationContextNotNull();
        return (T) webApplicationContext.getBean(name);
    }

    /**
     * 查找 Spring 容器中的 Bean 对象并返回。
     *
     * @param clazz Spring Bean 类型
     * @return Spring 容器定义的 Bean 对象
     *
     * @throws IllegalStateException
     */
    @SuppressWarnings(value = "unchecked")
    public static  T getBean(Class clazz) {
        checkApplicationContextNotNull();
        return (T) webApplicationContext.getBean(clazz);
    }

    /**
     * @throws IllegalStateException
     */
    private static void checkApplicationContextNotNull() {
        if (isNull(webApplicationContext)) {
            throw new IllegalStateException(
                            "ApplicationContextHolder is not initialized in spring container");
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy