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);
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wuyongde0922

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值