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();	
	}	
  • 创建自定义工厂,工厂里放入要拿的对象。
package com.caorui.factory;

import com.caorui.service.SomeService;
import com.caorui.service.impl.SomeServiceImpl;

public class ServiceFactory {

	//实例工厂创建bean对象
	public SomeService getSomeService() {
		SomeService someService = new SomeServiceImpl();
		return someService;
	}
}

然后配置好xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd">
	<!-- bean的定义:以下配置相当于SomeService service = new SomeServiceImpl(); id相当于service这个引用 -->
	<bean id="serviceFactory" class="com.caorui.factory.ServiceFactory"></bean>
	<!-- 从工厂中获取someServiceImpl的bean对象 -->
	<bean id="someService" factory-bean="serviceFactory" factory-method="getSomeService"></bean>
</beans>

或者这样配置也行。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd">
	 <!-- 从工厂中获取someServiceImpl的bean对象 //静态方式 -->
	<bean id="someService" class="com.caorui.factory.ServiceFactory" factory-method="getSomeService"></bean>
</beans>

serviceImpl层拿到需要的对象。

@Test
	public void testSome01() {
		//创建容器对象,ApplicationContext初始化时,所有容器中beans创建完毕
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		SomeService service = ac.getBean("someService", SomeService.class);
		service.doSome();
	}	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值