spring中加载Bean配置文件的常用方式

Spring中加载Bean配置文件的常用方式有两种,一种是通过实例化FileSystemXmlApplicationContext类的方式加载Bean,
另一种是通过实例化ClassPathXmlApplicationContext类的方式加载Bean.现举例如下,已做记录.

1.FileSystemXmlApplicationContext

(1)默认从项目工作路径开始查找,是相对路径

Java代码   收藏代码
  1. ApplicationContext applicationContext1 =  new  FileSystemXmlApplicationContext(  
  2.                 "src/main/java/org/springframework/abc/demo/beans.xml" );  


(2)如果加上file前缀,则表示绝对路径

Java代码   收藏代码
  1. ApplicationContext  applicationContext2 =  new  FileSystemXmlApplicationContext(  
  2.                 "file:E:/SpringSources/src/main/java/org/springframework/abc/demo/beans.xml" );  



2.ClassPathXmlApplicationContext

(1)没有前缀,默认为项目的classpath下相对路径

Java代码   收藏代码
  1. ApplicationContext applicationContext3 =  new  ClassPathXmlApplicationContext( "beans.xml" );  


(2)加上classpath前缀,表示项目的classpath下相对路径

Java代码   收藏代码
  1. ApplicationContext applicationContext4 =  new  ClassPathXmlApplicationContext(  
  2.                 "classpath:beans.xml" );  



3.DEMO代码如下

Java代码   收藏代码
  1. public   class  Test {  
  2.       
  3.     public   static   void  main(String[] args) {  
  4.   
  5.         ApplicationContext applicationContext1 = new  FileSystemXmlApplicationContext(  
  6.                 "file:E:/SpringSources/src/main/java/org/springframework/abc/demo/beans.xml" );  
  7.         System.out.println(applicationContext1.getBean("person" ));  
  8.   
  9.         ApplicationContext applicationContext2 = new  FileSystemXmlApplicationContext(  
  10.                 "src/main/java/org/springframework/abc/demo/beans.xml" );  
  11.         System.out.println(applicationContext2.getBean("person" ));  
  12.   
  13.         ApplicationContext applicationContext3 = new  FileSystemXmlApplicationContext(  
  14.                 "classpath:beans.xml" );  
  15.         System.out.println(applicationContext3.getBean("person" ));  
  16.   
  17.         ApplicationContext applicationContext4 = new  ClassPathXmlApplicationContext(  
  18.                 "beans.xml" );  
  19.         System.out.println(applicationContext4.getBean("person" ));  
  20.   
  21.         ApplicationContext applicationContext5 = new  ClassPathXmlApplicationContext(  
  22.                 "classpath:beans.xml" );  
  23.         System.out.println(applicationContext5.getBean("person" ));  
  24.   
  25.     }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值