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();
//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();
ApplicationContext接口提供了基础功能,ConfigurableApplicationContext接口对ApplicationContext接口实现了功能的追加
ClassPathXmlApplicationContext和FileSystemXmlApplicationContext是两个常用的实现类
ApplicationContext接口的上层接口是BeanFactory
BeanFactory是顶层接口
ApplicationContext常用接口
ConfigurableApplicationContext关闭容器的
ClassPathXmlApplicationContext是常用实现类:
ApplicationContext ctx = new ClassPathXmlApplicationContext(“applicationContext.xml”);
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();
}
}
加载bean的时机不同
public class BookDaoImpl implements BookDao{
public BookDaoImpl(){
System.out.println("constructor");
}
public void save(){
System.out.println("book dao save");
}
}
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
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">