zoukankan      html  css  js  c++  java
  • 使用beanFactory工厂实例化容器的方式实现单例模式

    //配置文件bean.properties(注意书写顺序)

    accountService=com.itheima.service.impl.AccountServiceImpl
    accountDao=com.itheima.dao.impl.AccountDaoImpl

    package com.hope.factory;

    import java.io.InputStream;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Properties;

    /**
    * @author newcityman
    * @date 2019/11/18 - 14:44
    * 第一个:需要一个配置文件来配置我们的service和dao
    * 第二个:通过读取配置文件中配置的内容,反射创建对象
    */
    public class BeanFactory {
    //定义一个properties对象
    public static Properties props;
    private static Map<String,Object> beans;
    //使用静态代码块为properties对象赋值
    static {
    try {
    //定义一个properties对象
    props = new Properties();
    //获取properties文件的流对象
    InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
    props.load(in);
    //实例化容器
    beans=new HashMap<String, Object>();
    //取出配置文件中所有的Key
    Enumeration keys = props.keys();
    //遍历枚举
    while(keys.hasMoreElements()){
    //取出每个key
    String key = keys.nextElement().toString();
    //根据key获取value
    String beanPath = props.getProperty(key);
    //反射创建对象
    Object value = Class.forName(beanPath).newInstance();
    //把key和value存入容器中
    beans.put(key,value);
    }
    } catch (Exception e) {
    throw new ExceptionInInitializerError("初始化propteies失败");
    }
    }

    /**
    * 根据bean的名称获取bean对象
    *
    * @param beanName
    * @return
    */
    public static Object getBean(String beanName) {

    return beans.get(beanName);
    }
    }

    package com.hope.ui;

    import com.hope.factory.BeanFactory;
    import com.hope.service.IAccountService;

    /**
    * @author newcityman
    * @date 2019/11/18 - 14:23
    */
    public class Client {

    public static void main(String[] args) {
    for (int i = 0; i < 5; i++) {
    IAccountService as = (IAccountService)BeanFactory.getBean("accountService");
    System.out.println(as);
    as.findAll();
    }
    }
     
  • 相关阅读:
    MySQL概述
    Seleniumselenium基础入门
    MySQL数据库的安装与使用
    元素定位_id
    Selenium浏览器的前进、后退、刷新
    元素定位_tag_name
    Selenium浏览器操作_窗口大小设置
    元素定位_name
    搭建maven服务器(repository)
    使用dos命令生成目录树
  • 原文地址:https://www.cnblogs.com/newcityboy/p/11885708.html
Copyright © 2011-2022 走看看