`
Notebookdong
  • 浏览: 121152 次
社区版块
存档分类
最新评论

Spring classpath:与classpath*:的区别

阅读更多

Spring可以通过指定classpath*:classpath:前缀加路径的方式从classpath加载文件,如bean的定义文件.

classpath*:的出现是为了从多个jar文件中加载相同的文件.

classpath:只能加载找到的第一个文件.

比如 resource1.jar中的package 'com.test.rs' 有一个 'jarAppcontext.xml' 文件,内容如下:

<bean name="ProcessorImplA" class="com.test.spring.di.ProcessorImplA" />

 resource2.jar中的package 'com.test.rs' 也有一个 'jarAppcontext.xml' 文件,内容如下:

<bean id="ProcessorImplB" class="com.test.spring.di.ProcessorImplB" />

 通过使用下面的代码则可以将两个jar包中的文件都加载进来

ApplicationContext ctx = new ClassPathXmlApplicationContext( "classpath*:com/test/rs/jarAppcontext.xml");

 而如果写成下面的代码,就只能找到其中的一个xml文件(顺序取决于jar包的加载顺序)

ApplicationContext ctx = new ClassPathXmlApplicationContext( "classpath:com/test/rs/jarAppcontext.xml");

 classpath*:的使用是为了多个component(最终发布成不同的jar包)并行开发,各自的bean定义文件按照一定的规则:package+filename,而使用这些component的调用者可以把这些文件都加载进来.classpath*:的加载使用了classloader的 getResources() 方法,如果是在不同的J2EE服务器上运行,由于应用服务器提供自己的classloader实现,它们在处理jar文件时的行为也许会有所不同。 要测试classpath*: 是否有效,可以用classloader从classpath中的jar文件里加载文件来进行测试:getClass().getClassLoader().getResources("<someFileInsideTheJar>")。(上面的例子是在sun的jre中运行的状态)

 

 从Spring的源码,在PathMatchingResourcePatternResolver类中,我们可以更清楚的了解其对的处理:如果是以classpath*开头,它会遍历classpath.

 

    protected Resource[] findAllClassPathResources(String location) throws IOException {  
        String path = location;  
        if (path.startsWith("/")) {  
            path = path.substring(1);  
        }  
        Enumeration resourceUrls = getClassLoader().getResources(path);  
        Set<Resource> result = new LinkedHashSet<Resource>(16);  
        while (resourceUrls.hasMoreElements()) {  
            URL url = (URL) resourceUrls.nextElement();  
            result.add(convertClassLoaderURL(url));  
        }  
        return result.toArray(new Resource[result.size()]);  
    }  
 另外在加载resource的时候,其他前缀的意义如下表所示:注意classpath*:只能用与指定配置文件的路径,不能用在用于 getResource的参数.如 appContext.getResource("classpath*:conf/bfactoryCtx.xml")会异常的.

 

 

前缀 例子 说明

classpath:

classpath:com/myapp/config.xml

从classpath中加载。

file:

file:/data/config.xml

作为 URL 从文件系统中加载。

http:

http://myserver/logo.png

作为 URL 加载。

(none)

/data/config.xml

根据 ApplicationContext 进行判断。

从Spring的源码可以看出原因:如果是classpath:开头,从classpath加载,否则尝试URL,如果失败,调用 getResourceByPath

 

    public Resource getResource(String location) {  
            Assert.notNull(location, "Location must not be null");  
            if (location.startsWith(CLASSPATH_URL_PREFIX)) {  
                return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());  
            }  
            else {  
                try {  
                    // Try to parse the location as a URL...  
                    URL url = new URL(location);  
                    return new UrlResource(url);  
                }  
                catch (MalformedURLException ex) {  
                    // No URL -> resolve as resource path.  
                    return getResourceByPath(location);  
                }  
            }  
        }  
 getResourceByPath会被不同ApplicationContext 实现覆盖.

 

如 GenericWebApplicationContext覆盖为如下:

    protected Resource getResourceByPath(String path) {  
            return new ServletContextResource(this.servletContext, path);  
        }  
      
    如 FileSystemXmlApplicationContext覆盖为如下:  
      
    protected Resource getResourceByPath(String path) {  
            if (path != null && path.startsWith("/")) {  
                path = path.substring(1);  
            }  
            return new FileSystemResource(path);  
        }  
 最终从文件加载的时候仍然是JAVA中常见的读取文件的方法:

如ClassPathResource得到inputstream的方法是利用class loader.

    public InputStream getInputStream() throws IOException {  
        InputStream is;  
        if (this.clazz != null) {  
            is = this.clazz.getResourceAsStream(this.path);  
        }  
 如FileSystemResource得到inputstream的方法是利用FileInputStream.

 

public InputStream getInputStream() throws IOException {
        return new FileInputStream(this.file);
    }
 如ServletContextResource得到inputstream的方法是利用servletContext.getResourceAsStream.

 

public InputStream getInputStream() throws IOException {  
    InputStream is = this.servletContext.getResourceAsStream(this.path);  
    if (is == null) {  
        throw new FileNotFoundException("Could not open " + getDescription());  
    }  
    return is;  
}  
 
 
 
分享到:
评论

相关推荐

    浅析Spring配置中的classpath:与classpath*:的区别

    主要介绍了Spring配置中的"classpath:"与"classpath*:"的区别,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

    springboot框架

    springboot mybatis management: security: enabled: false spring: profiles: active: local application: name: hh-store ... multipart: ... config: classpath:log4j2-${spring.profiles.active}.yml

    springboot+mybatis+内置tomcat示例.rar

    spring.thymeleaf.prefix=classpath:/templates/ #spring.thymeleaf.suffix=.jsp spring.thymeleaf.cache=false #mybatis 配置 mybatis.mapper-locations=classpath:mapping/*Mapper.xml mybatis.type-...

    spring源代码

    Resource[] resources = resolver.getResources("classpath*:META-INF/INDEX.LIST"); Assert.assertTrue(resources.length &gt; 1); //将加载多个模式匹配的Resource resources = resolver.getResources(...

    Spring中使用classpath加载配置文件浅析

    本文档介绍了spring中的在classpath中加载配置文件

    spring boot加载资源路径配置和classpath问题解决

    主要介绍了spring boot加载资源路径配置和classpath问题解决,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

    Spring通过在classpath自动扫描方式把组件纳入spring容器中管理

    NULL 博文链接:https://huangminwen.iteye.com/blog/1486843

    springboot logback 自定义配置

    在application.propertiesa或yml中添加自定义logback的设置 logging.config=classpath:config/logback-spring.xml,把config文件夹复制到resource下即可,logback-spring.xml不需要修改,路径和日志大小格式等配置在...

    springIOC核心组件分析.vsdx

    spring-beans:Bean工厂与装配 spring-context:上下文,即IOC容器 spring-context-support:对IOC的扩展,以及IOC子容器 spring-context-indexer:类管理组件和Classpath扫描 spring-expression:表达式语句 切面编程: ...

    SpringBoot实现本地存储文件上传及提供HTTP访问服务.docx

    文件上传目录自定义配置 怎么解决上述问题?别忘记了spring boot 为我们... static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}

    springboot学习

    Spring Boot 学习笔记 一、Spring Boot 简介 Spring Boot 是一个基于 Spring 框架的现代化 Java 框架,旨在简化...通过这个示例,我们可以学习 Spring Boot 的基本使用方法,以及如何与 MyBatis 和 JSP 进行集成。

    spring-boot-starter-mybatis:Spring Boot MyBatis入门

    春天启动启动器mybatis 这是MyBatis的非官方Spring Boot Starter 与官方相反,它遵循其他Spring Boot数据存储库的约定并实现适当...spring.mybatis.mapperLocations =classpath*:mapper/**/*.xml # mappers file spri

    Spring中PropertyPlaceholderConfigurer的使用

    这个 bean 的 `location` 属性指定了要加载的 Properties 文件的路径,在这里是 `classpath:/spring/include/dbQuery.properties`。 当存在多个 Properties 文件时,需要使用 `locations` 属性来指定多个文件的路径...

    maven相关资料

    Spring中ClassPathXmlApplicationContext类的简单使用 Posted on 2011-06-22 17:08 xcp 阅读(14689) 评论(0) 编辑 收藏 所属分类: Spring 一、简单的用ApplicationContext做测试的话,获得Spring中定义的Bean实例...

    毕设项目:基于SpringBoot+MyBatis-Plus 前后端分离的影院选座购票系统.zip

    spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/movie?characterEncoding=utf8&serverTimezone=UTC username: root password: 123456 cache: redis: #...

    Spring2.5 自动扫描classpath

    NULL 博文链接:https://hahalzb.iteye.com/blog/690802

    Spring高版本对ibatis的支持

    最近想在最新的Spring5.0中集成ibatis(不是mybatis),发现已经不在支持SqlmapClientTemplate和SqlmapClientFactoryBean,于是搞了这个工具jar来进行支持如下配置 &lt;bean id="sqlMapClient" class="org.spring...

    面试知识点总结--Spring 应用框架技术.pdf

    一、Spring 和 Struts 的区别 Spring 和 Struts 都是 Java 应用框架,但是它们有很大的不同。Struts 是一个基于 MVC 模式的 Web 层处理框架,而 Spring 则提供了通用的服务,包括 IOC/DI、AOP 等,关心的不仅仅是 ...

    基于java的企业级应用开发:Spring的核心容器.ppt

    spring/applicationContext.xml &lt;/param-value&gt; &lt;/context-param&gt; &lt;listener&gt; &lt;listener-class&gt; org.springframework.web.context.ContextLoaderListener &lt;/listener-class&gt; &lt;/listener&gt; ApplicationContext * * * *...

    xfire的使用详解

    &lt;param-value&gt;classpath:spring/app.xml,classpath:org/codehaus/xfire/spring/xfire.xml &lt;!--配置xfire ws--&gt; &lt;servlet-name&gt;XFireServlet &lt;servlet-class&gt;org.codehaus.xfire.spring....

Global site tag (gtag.js) - Google Analytics