通过工厂模式在Properties配置文件获取对象 出现 NullPointerException

博主在使用工厂模式从Properties配置文件创建对象时遇到NullPointerException。问题源于配置文件中的顺序与实例化顺序不一致。通过调整配置顺序解决了问题,但对原因仍困惑,寻求社区帮助。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题

在这里插入图片描述

我的properties文件

在这里插入图片描述

我的实现过程

#AccountDao接口
在这里插入图片描述

AccountDaoImpl实现类
在这里插入图片描述
AccountService接口
在这里插入图片描述
AccountServiceImpl实现类
在这里插入图片描述
Client类
在这里插入图片描述

BeanFactory类

package com.joey.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class BeanFactory {
    //定义一个Properties对象
    private static Properties properties;
    private static Map<String ,Object> beans;
    //使用静态代码块为properties对象赋值
    static{
        try {
            //实例化对象
            properties = new Properties();
            //获取properties文件的流对象
            InputStream inputStream = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            properties.load(inputStream);
            //实例化容器
            beans = new HashMap<String, Object>();
            //取出配置文件中的所有key
            Enumeration keys = properties.keys();
            //遍历枚举
            while(keys.hasMoreElements()){
                //取出每个Key
                String key = keys.nextElement().toString();
                //根据Key获取value
                String beanPath = properties.getProperty(key);
                //反射创建对象
                Object value = Class.forName(beanPath).newInstance();
                //把Key和Value存进容器
                beans.put(key,value);
            }
        } catch (IOException e) {
            throw new ExceptionInInitializerError("初始化properties失败");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Object getBean(String beanName) {
        return beans.get(beanName);
    }
}

问题解决方法

把properties文件的两个配置换一下位置

在这里插入图片描述

分析

properties.load(inputStream)执行了这一步后,配置文件的两个配置的顺序已经反了
在这里插入图片描述
Object value = Class.forName(beanPath).newInstance();
在这里插入图片描述

个人也不知道为什么会怎样,请各位大神赐教了!跪谢跪谢!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值