ITeye博客

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

snoopy7713 · 2012-10-18 09:07 · spring · 行业应用 · Spring · Bean · Markdown

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. public   static   void  main(String[] args) {
  3. ApplicationContext applicationContext1 = new  FileSystemXmlApplicationContext(
  4. "file:E:/SpringSources/src/main/java/org/springframework/abc/demo/beans.xml" );
  5. System.out.println(applicationContext1.getBean("person" ));
  6. ApplicationContext applicationContext2 = new  FileSystemXmlApplicationContext(
  7. "src/main/java/org/springframework/abc/demo/beans.xml" );
  8. System.out.println(applicationContext2.getBean("person" ));
  9. ApplicationContext applicationContext3 = new  FileSystemXmlApplicationContext(
  10. "classpath:beans.xml" );
  11. System.out.println(applicationContext3.getBean("person" ));
  12. ApplicationContext applicationContext4 = new  ClassPathXmlApplicationContext(
  13. "beans.xml" );
  14. System.out.println(applicationContext4.getBean("person" ));
  15. ApplicationContext applicationContext5 = new  ClassPathXmlApplicationContext(
  16. "classpath:beans.xml" );
  17. System.out.println(applicationContext5.getBean("person" ));
  18. }
  19. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。