zoukankan      html  css  js  c++  java
  • 静态获取Bean

    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.NoSuchBeanDefinitionException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    /**
    *

    • 静态获取Bean

    */
    public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext; 
    // 实现
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
    		throws BeansException {
    	SpringContextUtil.applicationContext = applicationContext;
    }
    
    public static ApplicationContext getApplicationContext() {
    	return applicationContext;
    }
    
    public static Object getBean(String name) throws BeansException {
    	try {
    		return applicationContext.getBean(name);
    	} catch (Exception e) {
    		e.getMessage();
    		throw new RuntimeException("获取的Bean不存在!");
    	}
    }
    
    public static <T> Object getBean(Class<T> zlass) throws BeansException {
    	try {
    		return applicationContext.getBean(zlass);
    	} catch (Exception e) {
    		e.getMessage();
    		throw new RuntimeException("获取的Bean不存在!");
    	}
    }
    
    public static <T> T getBean(String name, Class<T> requiredType)throws BeansException {
    	return applicationContext.getBean(name, requiredType);
    }
    
    public static boolean containsBean(String name) {
    	return applicationContext.containsBean(name);
    }
    
    public static boolean isSingleton(String name)
    		throws NoSuchBeanDefinitionException {
    	return applicationContext.isSingleton(name);
    }
    
    public static Class<? extends Object> getType(String name)
    		throws NoSuchBeanDefinitionException {
    	return applicationContext.getType(name);
    }
    
    public static String[] getAliases(String name)
    		throws NoSuchBeanDefinitionException {
    	return applicationContext.getAliases(name);
    }
    

    }

  • 相关阅读:
    docker国内镜像地址
    springBoot+websocket集群系列知识
    多个idea项目使用同一个tomcat
    nginx+tomcat遇到的https重定向到http问题
    设置常用错误页面自定义显示
    mysql关于索引的一些零碎知识点(持续更新)
    Idea使用Lombok简化实体类代码
    mysql索引分类及实现原理
    使用SpringSession和Redis解决分布式Session共享问题
    HashMap ConcurrentHashMap解读
  • 原文地址:https://www.cnblogs.com/cabinet/p/12839072.html
Copyright © 2011-2022 走看看