在学习Spring框架时遇到的问题

在使用注解注入数据时使用@Autowired@Qualifier("accountDao1")得到预期结果
使用@Resource(name = "accountDao2")则报错,

问题相关代码,请勿粘贴截图
package com.itheima.ui;

import com.itheima.dao.IAccountDao;


import com.itheima.service.IAccountService;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;


/*
* 模拟一个表现层,用于调用业务层
     */
    public static void main(String[] args) {
//        1.获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//        2.根据id获取bean对象
        IAccountService as = (IAccountService) ac.getBean("accountService");
//        System.out.println(as);
//        IAccountDao adao = ac.getBean("accountDao", IAccountDao.class);
//        System.out.println(adao);
        as.saveAccount();
    }
 }

@Service( "accountService")
public class AccountServiceImpl implements IAccountService {
//    @Autowired
//    @Qualifier("accountDao1")
    @Resource(name = "accountDao2")
    private  IAccountDao accountDao = null ;
    public void saveAccount(){
        accountDao.saveAccount();
    }
}

@Repository("accountDao2")
public class AccountDaoImpl2 implements IAccountDao {

    private IAccountDao accountDao ;
    public void saveAccount() {
        System.out.println("保存了账户222222");
    }
}


运行结果及报错内容

结果显示为Exception in thread "main" java.lang.NullPointerException
at com.itheima.service.impl.AccountServiceImpl.saveAccount(AccountServiceImpl.java:71)即accountDao.saveAccount();
at com.itheima.ui.Client.main(Client.java:32)即as.saveAccount();

我的解答思路和尝试过的方法
我想要达到的结果

我想知道怎么才能按预期运行得到结果为保存了账户222222
以及我错在哪里
感激不尽

如果使用@Autowired@Qualifier("accountDao2")也报错,那就说明accountDao2这个bean名字是有问题的。

bean的名字不是 accountDao2 但是类型是 IAccountDao

有用请采纳谢谢

img


你从bean.xml中拿的这个bean,是空的,注解数注入到了spring容器中