欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring中ClassPathXmlApplicationContext类的使用详解

程序员文章站 2022-06-17 22:38:10
classpathxmlapplicationcontext类的使用一、简单的用applicationcontext做测试获得spring中定义的bean实例(对象).可以用:applicationc...

classpathxmlapplicationcontext类的使用

一、简单的用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"));
  }
}

使用classpathxmlapplicationcontext遇到的问题

Spring中ClassPathXmlApplicationContext类的使用详解

上面执行main方法出错了,因为应该根据beforeadvice.class路径找到applicationcontext.xml,所以如下图就正常了:

Spring中ClassPathXmlApplicationContext类的使用详解

也可以如下图写法:

Spring中ClassPathXmlApplicationContext类的使用详解

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。