Spring IOC容器实现

   在Spring IOC 容器的代码是org.springframework.beans包中的BeanFactory接口,该接口提供了IOC容器的基本功能。

   而org.springframework.context包下的ApplicationContext接口扩展了BeanFactory,还提供了与Spring AOP集成、国际化处理、事件传播及提供不同层次的context实现 (如针对web应用的WebApplicationContext)。简单的说BeanFactory提供了IOC容器的最基本功能,而Application提供了更多的企业应用的支持。

 

      简单的对容器的实现做下总结。

 

 

import java.io.File;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
/**
 * IOC容器的实现
 * */
public class ContainerTest {
	/**
	 * beanfactory实现,从文件系统中获取资源
	 */
	@Test
	public void beanFactoryBaseonFileSystem(){
		//从文件系统中获取配置文件,默认为相对路径,也可以取绝对路径
		File file=new File("bin/resource/chapter01.xml");
		Resource resource=new FileSystemResource(file);
		//初始化容器
		BeanFactory bean=new XmlBeanFactory(resource);
		//从容器中获取bean
		GreetServiceImp service=bean.getBean("greetservice", GreetServiceImp.class);
		//执行操作
		service.sayGreeting();
	}
	/**
	 * beanfactory实现,从classpath获取资源
	 */
	@Test
	public void beanFactoryBaseOnClassPath(){
		//准备配置文件,从当前类加载路径中获取配置文件
		Resource resource=new ClassPathResource("resource/chapter01.xml");
		//初始化容器
		BeanFactory bean=new XmlBeanFactory(resource);
		//从容器中获取bean
		GreetServiceImp service=bean.getBean("greetservice", GreetServiceImp.class);
		//执行操作
		service.sayGreeting();
	}
	/**
	 * ApplicationContext实现,从文件系统中获取资源
	 */
	@Test
	public void applicationContextBaseOnFileSystem(){
		//准备配置文件,从文件系统中获取配置文件,默认为相当路径,也可以写绝对路径
		BeanFactory bean=new FileSystemXmlApplicationContext("bin/resource/chapter01.xml");
		//从容器中获取bean
		GreetServiceImp service=bean.getBean("greetservice", GreetServiceImp.class);
		//执行操作
		service.sayGreeting();
	}
	
	/**
	 * ApplicationContext实现,从ClassPath中获取资源
	 */
	@Test
	public void applicationContextBaseOnClassPath(){
		//准备配置文件,从当前类加载路径中获取配置文件
		BeanFactory bean=new ClassPathXmlApplicationContext("resource/chapter01.xml");
		//从容器中获取bean
		GreetServiceImp service=bean.getBean("greetservice",GreetServiceImp.class);
		//执行操作
		service.sayGreeting();
	}
}
 

      上述代码是IOC实现的常用几种方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值