首页 / 软件开发 / JAVA / spring入门(3) spring加载配置web
spring入门(3) spring加载配置web2013-07-18 史国旭 Spring初始化容器.三种经常用到的实现:一、ClassPathXmlApplicationContext:从类路径中加载。二、FileSystemXmlApplicationContext:从文件系统加载。三、XmlWebApplicationContext:从web系统中加载。使用1、bean工厂:最简单的容器,提供了基础的依赖注入支持。创建各种类型的Bean.BeanFactory factory = null ; //声明ClassPathResource resource = new ClassPathResource( "spring.xml" ); //类路径FileSystemResource fileSystemResource =new FileSystemResource( "D:\Ncode\mcode\sday02\src\spring.xml" );//系统路径//InputStreamResource res// = new InputStreamResource(// new FileInputStream("D:\ Ncode \ mcode \sday02\ src \spring.xml"));factory= new XmlBeanFactory(resource) ;//XmlBeanFactory(参数可以是resource或者fileSystemResource等//但是不能是 res 原因可以查看:文档Part III. Core Technologies 6. Resources// 中6.2 The Resource interface 有关isOpen方法的说明);factory = new ClassPathXmlApplicationContext( "spring.xml" );//从类路径中加载factory = newFileSystemXmlApplicationContext( "D:\Ncode\mcode\sday02\src\spring.xml" ); //从文件系统加载HelloService helloService =factory.getBean( "helloServiceImpl" , HelloServiceImpl. class );helloService.sayHello();使用2、应用上下文:建立在bean工厂基础之上,提供系统架构服务。ApplicationCotext,spring更加高级的容器。功能强大:1.提供文本信息解析工具,包括对国际化支持。2.提供载入文件资源的通用方法,如图片。3.可以向注册为监听器的bean发送事件。在很少的情况下,使用BeanFactory,如在移动设备。ApplicationContext context = newFileSystemXmlApplicationContext( "file:D:\Ncode\mcode\sday02\src\spring.xml" );context = newClassPathXmlApplicationContext( "classpath:spring.xml" );HelloService helloService =context.getBean( "helloServiceImpl" , HelloServiceImpl. class );helloService.sayHello();