Spring学习-Spring02-创建容器

Spring02-创建容器

1. 创建容器的三种方式
  • 直接new个对象。
//该方式的缺陷:当前测试类跟service实现类耦合到一起
	@Test
	public void testSome01() {
		SomeService someService = new SomeServiceImpl();
		someService.doSome();
	}
  • 创建ApplicationContext对象。
    • SomeService service = ac.getBean(“someServiceImpl”, SomeService.class);
      • "someServiceImpl"是.xml文件中bean标签中id。
      • SomeService.class是service的类型的class。
@Test
	public void testSome02() {
		//创建容器对象,ApplicationContext初始化时,所有容器中beans创建完毕
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		SomeService service = ac.getBean("someServiceImpl", SomeService.class);
		service.doSome();

	}
  • 创建Beanfactory对象。
@Test
	public void testSome03() {
		//创建容器对象,BeanFactory当调用getBean的时候获取相应对象时,才创建对象
		BeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
		SomeService service = bf.getBean("someServiceImpl", SomeService.class);
		service.doSome();	
	}	
发布了2 篇原创文章 · 获赞 0 · 访问量 17

猜你喜欢

转载自blog.csdn.net/Fu_si/article/details/104467077