package com.tianbo.analysis.bean; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * @ProjectName: * @Package: com.backstage.config * @ClassName: ApplicationContextProvider * @Description: 获取bean对象的工具类 * @Author: wangzhilong * @CreateDate: 2018/8/31 13:26 * @Version: 1.0 */ /** * Author:ZhuShangJin * Date:2018/7/3 */ @Component public class SpringBeanUtitl implements ApplicationContextAware{ private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // TODO Auto-generated method stub SpringBeanUtitl.applicationContext = applicationContext; } /** * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { if(name == null || applicationContext == null){ return null; } return (T) applicationContext.getBean(name); } /** * 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型. */ public static <T> T getBean(Class<T> clazz) { return applicationContext.getBean(clazz); } }