获取Spring的IOC容器对象的方式
从下面的类图中可以看出,ApplicationContext接口有很多的实现类,我们一般用到的是
ClassPathXmlApplicationContext、FileSystemXmlApplicationContext、AnnotationConfigApplicationContext这3个实现类,通过这3个实现类我们可以获取到Spring的IOC容器对象。
ClassPathXmlApplicationContext
ClassPathXmlApplicationContext用于在类路径下加载配置文件。
public void test1() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:bean.xml");
AccountService accountService = (AccountService) applicationContext.getBean("accountService");
System.out.println("accountService" + accountService);
AccountDaoImpl accountDao = applicationContext.getBean(AccountDaoImpl.class);
System.out.println("accountDao" + accountDao);
}
FileSystemXmlApplicationContext
FileSystemXmlApplicationContext用于在任意路径下加载配置文件。
@Test
public void test2() {
ApplicationContext ac = new FileSystemXmlApplicationContext("C:\\Users\\DELL\\Desktop\\bean.xml");
AccountService accountService = (AccountService) ac.getBean("accountService");
System.out.println("accountService" + accountService);
AccountDaoImpl accountDao = ac.getBean(AccountDaoImpl.class);
System.out.println("accountDao" + accountDao);
}
AnnotationConfigApplicationContext
AnnotationConfigApplicationContext用于读取注解。
总结
这个3种方式用的比较多的是第一种和第3种,第二种一般用的不多,因为配置文件随便乱放会造成问题;
核心容器的两个接口
ApplicationContext
在构建核心容器对象时,采用的是立即加载的方式,也就是说只要一读取配置文件就创建配置文件中的对象。
BeanFactory
在构建核心容器对象时,采用的是延迟加载的方式,也就是说什么时候获取对象了,什么时候才创建对象。
@Test
public void test3() {
Resource resource = new ClassPathResource("classpath:bean.xml");;
BeanFactory beanFactory = new XmlBeanFactory(resource);
AccountService accountService = (AccountService)beanFactory.getBean("accountService");
}