NullPointerException关于在spring工厂类BeanFactory加载过程中的bug

本文探讨了一个Spring Boot应用中,如何在循环依赖场景下正确注入`IAccountService`和`IAccountDao`,并解析了静态代码块和bean工厂初始化过程中的问题。通过实例展示了如何避免`NullPointerException`,提高代码健壮性。
摘要由CSDN通过智能技术生成
public class Client {
    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 5; i++) {
            IAccountService accountService = (IAccountService)BeanFactory.getBean("accountService");
            accountService.saveAccount();
        }
    }
}
public class AccountServiceImpl implements IAccountService{

    private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao");

    public void saveAccount() {
        int i = 1;
        //建议按注释写法来
        //accountDao = (IAccountDao) BeanFactory.getBean("accountDao");
        accountDao.saveAcoount();
        System.out.println(i);
        i++;
    }
}
public class BeanFactory {
    private static Properties prop;
    private static Map<String,Object> maps;

    static {
        try {
            System.out.println("static代码块开始执行"+System.currentTimeMillis());
            prop=new Properties();
            prop.load(BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"));
            maps = new HashMap<>();
            Enumeration keys = prop.keys();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement().toString();
                String beanPath = prop.getProperty(key);
                System.out.println(key+"  "+System.currentTimeMillis());
                //这一条会创建对象,导致serviceImpl中的dao也会创建对象,从而导致空指针
                Object value = Class.forName(beanPath).newInstance();

                maps.put(key,value);
            }
            System.out.println("maps容器添加完成"+System.currentTimeMillis());
        } catch (Exception e) {
            throw new ExceptionInInitializerError("初始化fail");
        }
    }

    public static Object getBean(String beanName){
        System.out.println("getbean方法"+beanName+"    "+maps.get("accountDao")+"  "+System.currentTimeMillis());
        return maps.get(beanName);
    }
}
//以下是打印日志
static代码块开始执行1623141072552
accountService  1623141072651
getbean方法accountDao    null  1623141072671
accountDao  1623141072727
maps容器添加完成1623141072728
getbean方法accountService    com.echo233.dao.AccountDaoImpl@9f70c54  1623141072728
Exception in thread "main" java.lang.NullPointerException
	at com.echo233.service.AccountServiceImpl.saveAccount(AccountServiceImpl.java:14)
	at com.echo233.ui.Client.main(Client.java:11)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值