9 容器
9.1 获取容器
- 记载类路径下的容器所在的配置文件,也就是之前用的
public class App2 {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BookDao bookDao = (BookDao) ctx.getBean("bookDao");
bookDao.save();
}
}
- 使用文件的绝对位置,少用
//2. 使用文件的绝对位置,哪个盘符下进行加载
ApplicationContext ctx2 = new FileSystemXmlApplicationContext("C:\\Users\\CZyue\\Desktop\\javaSE\\10-ssm\\spring_10_container\\spring_10_container\\src\\main\\resources\\applicationContext.xml");
BookDao bookDao = (BookDao) ctx2.getBean("bookDao");
bookDao.save();
- 总结
9.2 获取bean
- 通过强转类型
//1.1获取bean,通过强转类型
BookDao bookDao = (BookDao) ctx.getBean("bookDao");
bookDao.save();
- 第二个参数指定类型
BookDao bookDao = ctx.getBean("bookDao", BookDao.class);
bookDao.save();
- 按照类型找
//1.3 按照类型找,要求容器中只有一个就好,不然找不到
BookDao bookDao = ctx.getBean(BookDao.class);
bookDao.save();
- 总结
9.3 容器类层次结构
- ApplicationContext,ConfigurableApplicationContext接口
-
ApplicationContext接口提供了基础功能,ConfigurableApplicationContext接口对ApplicationContext接口实现了功能的追加
-
ClassPathXmlApplicationContext和FileSystemXmlApplicationContext是两个常用的实现类
-
ApplicationContext接口的上层接口是BeanFactory
- 容器类结构图
BeanFactory是顶层接口
ApplicationContext常用接口
ConfigurableApplicationContext关闭容器的
ClassPathXmlApplicationContext是常用实现类:
ApplicationContext ctx = new ClassPathXmlApplicationContext(“applicationContext.xml”);
9.4 BeanFactory
- 代码
- AppForBeanFactory
BeanFactory来获取容器,通过ClassPathResource来造resources,然后把xml传进去
public class AppForBeanFactory {
public static void main(String[] args) {
Resource resources = new ClassPathResource("applicationContext.xml");
BeanFactory bf = new XmlBeanFactory(resources);
BookDao bookDao = bf.getBean(BookDao.class);
bookDao.save();
}
}
- 和ApplicationContext获取容器的区别
加载bean的时机不同
- 接口实现类BookDaoImpl写一个构造器
public class BookDaoImpl implements BookDao{
public BookDaoImpl(){
System.out.println("constructor");
}
public void save(){
System.out.println("book dao save");
}
}
- 用BeanFactory获取bean
public class AppForBeanFactory {
public static void main(String[] args) {
Resource resources = new ClassPathResource("applicationContext.xml");
BeanFactory bf = new XmlBeanFactory(resources);
}
}
- 结果
Process finished with exit code 0
- 用ApplicationContext获取bean
public class App2 {
public static void main(String[] args) {
//1.记载类路径下的配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
}
- 结果
ApplicationContext初始化会提前加载
constructor
Process finished with exit code 0
如果要延迟,可以在appliacation.xnl中延迟加载
<bean id = "bookDao" class="com.itheima.dao.impl.BookDaoImpl" lazy-init="true">