三个实现类:
-
ClassPathXmlApplicationContext 读取类路径下的xml作为配置文件(配置文件在项目中)
-
FileSystemXmlApplicationContext 读取本地目录下的xml作为配置文件(配置文件在外部)
-
AnnotationConfigApplicationContext 读取一个Java类作为配置文件(读取注解配置)
/** * 从IOC容器中获取对象 */ @Override public void save(Account account) { //1. 加载配置文件,初始化IOC容器 ApplicationContext applicationContext = //new ClassPathXmlApplicationContext("applicationContext.xml"); new FileSystemXmlApplicationContext("C:\\applicationContext.xml"); //2. 从容器中获取对象 AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao"); accountDao.save(account); }
1个方法:
-
getBean() 用于从Spring容器中获取Bean对象,参数可以使用三种情况:
-
getBean("id") 使用bean的id从容器中查找对象
-
getBean(Bean.class) 使用bean的class类型从容器中查找对象,有多个子类会报异常
-
getBean("id", Bean.class) 使用bean的id 和 class类型从容器中查找对象
-
//2. 从容器中获取对象
AccountDao accountDao =
//(AccountDao) xmlApplicationContext.getBean("accountDao");
//(AccountDao) xmlApplicationContext.getBean(AccountDao.class);
(AccountDao) applicationContext.getBean("accountDao2",AccountDao.class);