zoukankan      html  css  js  c++  java
  • java获取spring的bean

    /**
     * 载入spring配置文件,提供getBean接口.
     * @author xiongzy
     *
     */
    public final class BeanLocator {
        private static final Logger logger = Logger.getLogger(BeanLocator.class);
        /**
         * 单实例.
         */
        private static BeanLocator instance = null;
        
        /**
         * 缺省配置文件名.
         */
        private static final String DEFAULT_CONFIGURATION_FILENAME = "spring/applicationContext.xml";
        
        /**
         * 载入配置文件名称.
         */
        private static String configurationFileName = null;
        
        /**
         * spring环境.
         */
        private ApplicationContext applicationContext = null;

        /**
         * 单例模式.
         * @return 接口
         */
        public static BeanLocator getInstance() {
            if (instance == null) {
                // 同步控制代码, 防止初始化多次.
                synchronized(logger) {
                    if (instance == null) {
                        instance = new BeanLocator();
                    }
                }
            }
            return instance;
        }

        /**
         * 设置配置文件名称.
         * @param fileName 配置文件名称
         */
        public static void setConfigurationFileName(String fileName) {
            configurationFileName = fileName;
        }

        
        /**
         * 私有构造.
         */
        private BeanLocator() {
            if (configurationFileName == null || configurationFileName.length() == 0) {
                configurationFileName = DEFAULT_CONFIGURATION_FILENAME;
            }
            // 得到spring框架bean环境
            try{
                applicationContext = new ClassPathXmlApplicationContext(configurationFileName);
            }catch(Exception e){
                logger.error("初始化spring配置文件时发生异常:" + e.getMessage(), e);
                throw new RuntimeException("初始化spring配置文件时发生异常:" + e.getMessage(), e);
            }
        }

        /**
         * spring getBean 接口.
         * @param beanName 接口名称
         * @return 接口
         */
        public Object getBean(String beanName) {
            return applicationContext.getBean(beanName);

        }

        public static void main(String[] args) {
            CityInfoService cityInfoService = (CityInfoService)BeanLocator.getInstance().getBean("cityInfoService");
            System.out.println(cityInfoService);
        }

    }

  • 相关阅读:
    配置postgres9.3间的fdw——实现不同postgres数据库间的互访问
    linux安装配置postgres及使用dblink
    一次“峰回路转”的troubleshooting经历
    10分钟内把永远跑不完的存储过程变为2秒跑完
    C++ friend关键字
    每天学点Linux命令之 vi 命令
    Shell
    九大排序算法及其实现- 插入.冒泡.选择.归并.快速.堆排序.计数.基数.桶排序.堆排序
    到位
    【LeetCode】-- 260. Single Number III
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/7123108.html
Copyright © 2011-2022 走看看