SpringContextUtil.java 1.14 KB
package com.cjs.site.util.lang;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * Spring手动获取Bean
 * 
 * @author tongyufu
 *
 */
@Lazy(false)
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static Object getBean(String beanName) {
        return SpringContextUtil.context.getBean(beanName);
    }

    public static <T> T getBean(Class<T> requiredType) {
        return SpringContextUtil.context.getBean(requiredType);
    }

    public static <T> T getBean(String beanName, Class<T> requiredType) {
        return SpringContextUtil.context.getBean(beanName, requiredType);
    }
}