Application初始化

BeanFactory有很多实现类,通常使用org.springframework.beans.factory.xml.XmlBeanFactory类。但对于大部分J2EE应用而言,推荐使用ApplicationContext. ApplicationContext是 

BeanFactory的子接口,其常用实现类是org.springframework.context.support.FileSystemXmlApplicationContext和org.springframework.context.support.ClassXmlAplicationContext。 
Springr的配置信息通常采用XML配置文件来设置,因此,创建BeanFactory实例时,应该提供XML配置文件作为参数。、 

下面详细介绍ApplicationContext的实际运用: 



一:ClassPathXmlApplicationContext 
1.没有前缀:默认为项目的classpath下相对路径 
   ApplicationContext appCt = new ClassPathXmlApplicationContext("app.spring.xml"); 

2.前缀classpath:表示的是项目的classpath下相对路径 
   ApplicationContext appCt = new ClassPathXmlApplicationContext("classpath:app.spring.xml"); 

3.使用前缀file 表示的是文件的绝对路径 
   ApplicationContext appCt = new ClassPathXmlApplicationContext("file:D:/app.spring.xml"); 

4.可以同时加载多个文件 
  String[] xmlCfg = new String[] { "classpath:base.spring.xml","app.spring.xml"}; 
  ApplicationContext appCt = new ClassPathXmlApplicationContext(xmlCfg); 

5.使用通配符加载所有符合要求的文件 
  ApplicationContext appCt = new ClassPathXmlApplicationContext("*.spring.xml"); 

二:FileSystemXmlApplicationContext 
1.默认为项目工作路径 即项目的根目录 
ApplicationContext appCt2 = new FileSystemXmlApplicationContext("src/main/resources/app.spring.xml"); 

2.前缀classpath:表示的是项目的classpath下相对路径 
   ApplicationContext appCt2 = new FileSystemXmlApplicationContext("classpath:app.spring.xml"); 

3.使用前缀file 表示的是文件的绝对路径 
   ApplicationContext appCt2 = new FileSystemXmlApplicationContext("file:D:/app.spring.xml"); 
   ApplicationContext appCt2 = new FileSystemXmlApplicationContext("D:/app.spring.xml"); 

4.可以同时加载多个文件 
  String[] xmlCfg = new String[] { "src/main/resources/base.spring.xml","classpath:app.spring.xml"}; 
  ApplicationContext appCt2 = new FileSystemXmlApplicationContext(xmlCfg); 

5.使用通配符加载所有符合要求的文件 
  ApplicationContext appCt2 = new FileSystemXmlApplicationContext("classpath:*.spring.xml"); 


6.Resource 

ResourcePatternResolver     resolver=new PathmatchingResourceResolver(); 
Resource   res = resolver.getResource("classpath:com/hh/beans.xml"); 
Beanfactory    bf = new  XmlBeanFactory(res); 
Car  car= bf.getBean("car",Car.class) 

猜你喜欢

转载自dwj147258.iteye.com/blog/2363701