zoukankan      html  css  js  c++  java
  • Spring通过配置文件获取bean(不用IOC)

    1.写一个SpringContext的工具类 实现ApplicationContextAware接口

     1 import org.springframework.beans.BeansException;
     2 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
     3 import org.springframework.context.ApplicationContext;
     4 import org.springframework.context.ApplicationContextAware;
     5 
     6 public class SpringContextUtil implements ApplicationContextAware{
     7     
     8     private static ApplicationContext applicationContext;     //Spring应用上下文环境
     9 
    10      public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    11        SpringContextUtil.applicationContext = applicationContext;
    12      }
    13      
    14      public static ApplicationContext getApplicationContext() {
    15        return applicationContext;
    16      }
    17 
    18      public static Object getBean(String name) throws BeansException {
    19        return applicationContext.getBean(name);
    20      }
    21 
    22      public static Object getBean(String name, Class requiredType) throws BeansException {
    23        return applicationContext.getBean(name, requiredType);
    24      }
    25 
    26      public static boolean containsBean(String name) {
    27        return applicationContext.containsBean(name);
    28      }
    29 
    30      public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
    31        return applicationContext.isSingleton(name);
    32      }
    33 
    34      public static Class getType(String name) throws NoSuchBeanDefinitionException {
    35        return applicationContext.getType(name);
    36      }
    37 
    38      public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
    39        return applicationContext.getAliases(name);
    40      }
    41 
    42 }
    View Code

    2,Spring配置文件中添加关于该工具类的bean配置

     <bean id="SpringContextUtil " class="util.SpringContextUtil "  />

    3.代码中使用

    MongoTemplate temp = (MongoTemplate)SpringContextUtil.getBean("mongoTemplate");
  • 相关阅读:
    JS异错面试题
    CSG
    OBS工具汇总
    SFS OBS
    zookeeper配置文件
    zookeeper概念
    centos yum源问题三板斧
    nexus仓库
    SVN备份恢复
    ubuntu
  • 原文地址:https://www.cnblogs.com/dobestself-994395/p/4568011.html
Copyright © 2011-2022 走看看