错误描述:
首先这是我的工厂类:
public class BeanFactory {
//定义一个Properities对象
private static Properties props;
//定义一个Map,用于存放我们要创建的对象,我们把它称为容器
private static Map beans;
//使用静态代码块为Properities赋值
static{
try{
//实例化对象
props=new Properties();
//获取Properities文件的流对象
InputStream in=BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
props.load(in);
//实例化容器
beans=new HashMap();
//取出配置文件中所有的key
Enumeration
这是我的持久层接口:
public interface IAccountDao {
void saveAccount();
}
持久层实现类:
public class AccountDaoImpl implements IAccountDao {
public void saveAccount()
{
System.out.println("已经保存了账户");
}
业务层接口:
public interface IAccountService {
void saveAccount();
}
业务层实现类:
```css
public class AccountServiceImpl implements IAccountService
{
//private IAccountDao accountDao=new AccountDaoImpl();
IAccountDao accountDao= (IAccountDao) BeanFactory.getBean("accountDao");
public void saveAccount(){
accountDao.saveAccount();
}
}
测试类
public class Client {
public static void main(String[] args)
{
//IAccountService accountService=new AccountServiceImpl();
IAccountService as= (IAccountService)BeanFactory.getBean("accountService");
as.saveAccount();
}
}
配置bean.properties文件:
accountService=com.wwh.service.impl.AccountServiceImpl accountDao=com.wwh.dao.impl.AccountDaoImpl
运行报错,空指针异常:
原因:
使用Class.forName()时候, java会自动初始化要加载的类, 在上述例子中,要生产的类BeanFactory中恰好用用到了工厂类Class.forName(beanPath),要生产的对象在类初始化中恰好也用到工厂类:IAccountDao accountDao= (IAccountDao) BeanFactory.getBean(“accountDao”);
导致抛出空指针异常:NullPointerException异常
解决方法
将变量赋值放在方法中,这样生产的对象所在类在初始化时不会用到工厂类:
public class AccountServiceImpl implements IAccountService
{
//private IAccountDao accountDao=new AccountDaoImpl();
IAccountDao accountDao= null;
public void saveAccount(){
accountDao=(IAccountDao) BeanFactory.getBean("accountDao");
accountDao.saveAccount();
}
}
成功运行截图:



