ClassPathResource、ClassPathXMlResource、ClassPathXmlApplicationContext

spring读取配置文件方式

方法一:在初始化时保存ApplicationContext对象
代码:
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("beanId");
说明:
这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。


方法二:通过Spring提供的工具类获取ApplicationContext对象
代码:

import org.springframework.web.context.support.WebApplicationContextUtils;


ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc)
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc)
ac1.getBean("beanId");
ac2.getBean("beanId");
说明:
这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后在通过它获取需要的类实例。
上面两个工具方式的区别是,前者在获取失败时抛出异常,后者返回null。


方法三:继承自抽象类ApplicationObjectSupport
说明:
抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到ApplicationContext。Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。

方法四:继承自抽象类WebApplicationObjectSupport
说明:
类似上面方法,调用getWebApplicationContext()获取WebApplicationContext

方法五:实现接口ApplicationContextAware
说明:
实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。Spring初始化时,会通过该方法将ApplicationContext 对象注入。

以上方法适合不同的情况,请根据具体情况选用相应的方法。

特别声明:

  当在spring中导入另外的文件时,使用ClassPathXMLResource

  使用动态加载时,使用ClassPathXmlApplicationContext

原因还不知道

这里值得提一点的是,系统中用到上述方法的类实际上就于Spring框架紧密耦合在一起了,因为这些类是知道它们是运行在Spring框架上的,因此,系统中,应该尽量的减少这类应用,使系统尽可能的独立于当前运行环境,尽量通过DI的方式获取需要的服务提供者。

二.读取xml文件

/**
* 利用XmlBeanFactory(Resource resource)
* 这里Resource必须是xml格式
* Resource包括:AbstractResource, ClassPathResource, FileSystemResource,
* InputStreamResource, ServletContextResource, UrlResource
*/


/*
* 利用 InputStreamResource(InputStream inputStream)
* 要将applicationContext.xml放在项目根目录下
*/
InputStream is = null;
try {
is = new FileInputStream("applicationContext.xml");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Resource resource = new InputStreamResource(is);
BeanFactory factory = new XmlBeanFactory(resource);
UserDao userDao = (UserDao)factory.getBean("userDao");

/*
* 利用 Properties
* 要将bean.properties放在类路径--源文件夹(src)目录下
*/

这里介绍两种技术:利用spring读取properties 文件和利用java.util.Properties读取
(一)利用spring读取properties 文件
利用org.springframework.beans.factory.support.PropertiesBeanDefinitionReader来读取属性文件

构造如下config.properties文件properties代码

userDao.class=com.spring.dao.UserDao

属性文件中的"userDao"名称即是Bean的别名设定,.class用于指定类来源。
然后利用org.springframework.beans.factory.support.PropertiesBeanDefinitionReader来读取属性文件
   BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
   PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(reg);
   reader.loadBeanDefinitions(new ClassPathResource("config.properties"));
   BeanFactory factory = (BeanFactory)reg;
   UserDao userDao = (UserDao)factory.getBean("userDao");
(二)利用java.util.Properties读取属性文件
1.    String str=File.separator;
        InputStream path=this.getServletContext().getResourceAsStream(str+"WEB-INF"+str+"classes"+str+"password.properties");
        //InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("password.properties");

    /*File filepath=new File(this.getServletContext().getRealPath(str+"WEB-INF"+str+"classes")+str+"password.properties");

        InputStream path=new FileInputStream(filepath);*/
        Properties pros = new Properties();
        try {
            pros.load(path);
        } catch (IOException ex) {
            //System.out.println("file is not exist");
            errorMessage="资源文件不存在";
        }
        System.out.println("username:"+p.getProperty("username")+",password:"+p.getProperty("password"));

2.    import org.springframework.core.io.ClassPathResource;

        ClassPathResource cr = new ClassPathResource("password.properties");//会重新加载spring框架
        Properties pros = new Properties();
        try {
            pros.load(cr.getInputStream());
        } catch (IOException ex) {
            //System.out.println("file is not exist");
            errorMessage="资源文件不存在";
        }

1.利用ClassPathXmlApplicationContext

可以从classpath中读取XML文件

(1) ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao)context.getBean("userDao");

(2) ClassPathXmlApplicationContext resource = new ClassPathXmlApplicationContext(new  String[]{"applicationContext-ibatis-oracle.xml","applicationContext.xml","applicationContext-data-oracle.xml"});

BeanFactory factory = resource;

UserDao userDao = (UserDao) factory.getBean("userDao");

2. 利用ClassPathResource

可以从classpath中读取XML文件

Resource cr = new ClassPathResource("applicationContext.xml");

BeanFactory bf=new XmlBeanFactory(cr);

UserDao userDao = (UserDao)bf.getBean("userDao");

加载一个xml文件org.springframework.beans.factory.config.PropertyPlaceholderConfigurer不起作用

3.利用XmlWebApplicationContext读取

从Web应用程序的文件架构中,指定相对位置来读取定义文件。

XmlWebApplicationContext ctx = new XmlWebApplicationContext();
ctx.setConfigLocations(new String[] {"/WEB-INF/ applicationContext.xml");
ctx.setServletContext(pageContext.getServletContext());
ctx.refresh();
UserDao  userDao = (UserDao ) ctx.getBean("userDao ");

4.利用FileSystemResource读取

Resource rs = new FileSystemResource("D:/tomcat/webapps/test/WEB-INF/classes/ applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(rs);
UserDao  userDao  = (UserDao )factory.getBean("userDao");

值得注意的是:利用FileSystemResource,则配置文件必须放在project直接目录下,或者写明绝对路径,否则就会抛出找不到文件的异常

 

5.利用FileSystemXmlApplicationContext读取

可以指定XML定义文件的相对路径或者绝对路径来读取定义文件。

方法一:

String[]   path={"WebRoot/WEB-INF/applicationContext.xml","WebRoot/WEB-INF/applicationContext_task.xml"};
ApplicationContext context = new FileSystemXmlApplicationContext(path);


方法二:

String path="WebRoot/WEB-INF/applicationContext*.xml";
ApplicationContext context = new FileSystemXmlApplicationContext(path);

方法三:
ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:地址");
没有classpath的话就是从当前的工作目录

 

启动Spring框架

1.

ApplicationContext context = new ClassPathXmlApplicationContext(
    "beans.xml", this.getClass());

2

.Resource res = new ClassPathResource("1.xml");
   BeanFactory factory = new XmlBeanFactory(res);
   SayHello bean1 = (SayHello) factory.getBean("hello");

 

1.简单的用ApplicationContext做测试的话,获得Spring中定义的Bean实例(对象).可以用:

ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
RegisterDAO registerDAO = (RegisterDAO)ac.getBean("RegisterDAO");

如果是两个以上:
ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml","dao.xml"});

或者用通配符:
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:/*.xml");


、ClassPathXmlApplicationContext[只能读放在web-info/classes目录下的配置文件]和FileSystemXmlApplicationContext的区别

classpath:前缀是不需要的,默认就是指项目的classpath路径下面;
如果要使用绝对路径,需要加上file:前缀表示这是绝对路径;

对于FileSystemXmlApplicationContext:
默认表示的是两种:

1.没有盘符的是项目工作路径,即项目的根目录;
2.有盘符表示的是文件绝对路径.

如果要使用classpath路径,需要前缀classpath:

public class HelloClient {

  protected static final Log log = LogFactory.getLog(HelloClient.class);

  public static void main(String[] args) {
    // Resource resource = new ClassPathResource("appcontext.xml");
    // BeanFactory factory = new XmlBeanFactory(resource);

    // 用classpath路径
    // ApplicationContext factory = new ClassPathXmlApplicationContext("classpath:appcontext.xml");
    // ApplicationContext factory = new ClassPathXmlApplicationContext("appcontext.xml");

    // ClassPathXmlApplicationContext使用了file前缀是可以使用绝对路径的
    // ApplicationContext factory = new ClassPathXmlApplicationContext("file:F:/workspace/example/src/appcontext.xml");

    // 用文件系统的路径,默认指项目的根路径
    // ApplicationContext factory = new FileSystemXmlApplicationContext("src/appcontext.xml");
    // ApplicationContext factory = new FileSystemXmlApplicationContext("webRoot/WEB-INF/appcontext.xml");

    // 使用了classpath:前缀,这样,FileSystemXmlApplicationContext也能够读取classpath下的相对路径
    // ApplicationContext factory = new FileSystemXmlApplicationContext("classpath:appcontext.xml");
    // ApplicationContext factory = new FileSystemXmlApplicationContext("file:F:/workspace/example/src/appcontext.xml");

    // 不加file前缀
    ApplicationContext factory = new FileSystemXmlApplicationContext("F:/workspace/example/src/appcontext.xml");
    IHelloWorld hw = (IHelloWorld)factory.getBean("helloworldbean");
    log.info(hw.getContent("luoshifei"));
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值