Spring容器实例化(非web环境下)

如下介绍的几种实现容器实例化的方法,是非web环境下的常见方式

(1)从classpath路径下加载

Resource resource=new FileSystemResource("E:\\proj\\applicationContext.xml");
XmlBeanFactory bean=new XmlBeanFactory(resource);

 文件

   通过这种方式加载,需要将Spring的配置文件放到当前项目的classpath路径下,这里所说的classpath指的就是你的应用程序的src的目录,在web环境下,src目录下的源文件经编译后,会自动移到WEB-INF\class目录。

 

(2)从文件系统中加载applicationContext.xml文件

    这种方式使用FileSystemResource来指定Spring配置文件的位置

Resource resource=new ClassPathResource("applicationContext.xml");
XmlBeanFactory bean=new XmlBeanFactory(resource);
BizInterface biz=(BizInterface)bean.getBean("beanid");

 

(3)从输入流中applicationContext.xml文件

InputStream因为是抽象类,不能直接实例化,通常使用FileInputStream来获取一个文件流,才用这种方式,同上面提到的从文件系统加载配置文件的方式一样,Spring配置文件可以在硬盘的任意位置。

InputStream is=new FileInputStream("E:\\proj\\applicationContext.xml");
Resource resource=new InputStreamResource(is);
XmlBeanFactory bean=new XmlBeanFactory(resource);

 

(4)基于多配置文件的加载

可以加载单个或多个配置文件

String [] configFile={"applicationContext1.xml,applicationContext2.xml"};
ApplicationContext ac=ClassPathXmlApplicationContext(configFile);
BeanFactory bean=(BeanFactory)ac;

 

这里指定的文件路径是当前目录的classpath路径

你可能感兴趣的:(spring,Web,bean,xml)