Spring > 模拟编写配置文件和工厂类

编写Dao层的实现类和接口

在这里插入图片描述
在这里插入图片描述

配置文件的编写

首先要确定本类的Id,然后还有本类的全类名
在这里插入图片描述

实现工厂类

public class BeansFactory {
    
    
    private static Properties beans = null;

    static {
    
    
        beans = new Properties();
        // 获取配置信息
        InputStream beans_path = BeansFactory.class.getClassLoader().getResourceAsStream("./BeanMapper.properties");
        try {
    
    
            beans.load(beans_path);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

    // 获取Bean对象
    public static <T> T getBean(String className, T t) {
    
    
    	// 获取ClassName所对应的全路径名称
        Object o = beans.get(className);
        // 设置接受全路径名称的变量
        String classPath = null;
        if (o == null) {
    
    
            // 获取到的className的为空
            System.out.println("ClassNameNotFound : " + className);
        } else {
    
    
            // 不为空
            // 判断获取到的classPath是否为String类型
            if (o.getClass().getName().contains("String")) {
    
    
                // 是String类型,转化为String类型
                classPath = (String) o;
            } else {
    
    
                // 获取到的值不为String类型,则直接抛出异常
                try {
    
    
                    throw new ClassNotFoundException();
                } catch (ClassNotFoundException e) {
    
    
                    e.printStackTrace();
                }
            }
        }

        try {
    
    
        	// 根据传来的对象的类型  进行转换
            t = (T)Class.forName(classPath).newInstance();
        } catch (InstantiationException e) {
    
    
            e.printStackTrace();
        } catch (IllegalAccessException e) {
    
    
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        }

        return t;
    }
}

执行程序 结果如下

在这里插入图片描述

这样写的意义在于降低耦合,但是不能完全意义没有耦合,完全意义上没有耦合只能证明其中一个类没有存在的意义

猜你喜欢

转载自blog.csdn.net/weixin_43309893/article/details/119524035