classpath 订阅
Classpath设置的目的,在于告诉Java执行环境,在哪些目录下可以找到您所要执行的Java程序所需要的类或者包。 展开全文
Classpath设置的目的,在于告诉Java执行环境,在哪些目录下可以找到您所要执行的Java程序所需要的类或者包。
信息
外文名
Classpath
设置方法
在系统变量中新增Classpath变量
用    途
告诉Java执行环境
中文名
类路径
CLASSPATH简介
设置Classpath的目的,在于告诉Java执行环境,在哪些目录下可以找到您所要执行的Java程序所需要的类或者包。
收起全文
精华内容
下载资源
问答
  • 主要介绍了Spring配置中的"classpath:"与"classpath*:"的区别,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
  • 主要介绍了Java 中获取类路径 classpath 的方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下
  • 主要介绍了spring boot加载资源路径配置和classpath问题解决,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
  • 主要介绍了浅谈web项目读取classpath路径下面的文件,具有一定借鉴价值,需要的朋友可以参考下
  • 下面小编就为大家带来一篇Java中获取类路径classpath的简单方法(推荐)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
  • 主要介绍了java动态添加外部jar包到classpath的实例详解的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下
  • 为何配置path?为何配置classpath?当时初学java时只是关心如何做而不去关心这些问题,接下来介绍一下,感兴趣的朋友可以参考下哦
  • 主要介绍了android studio 3.6.1导入项目报错提示无法下载classpath里的内容,本文通过原因分析通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
  • Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all artifacts for configuration ‘:classpath’. 原因: 百度说是无法下载...
  • NULL 博文链接:https://foreversky12.iteye.com/blog/2325785
  • Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all artifacts for configuration ‘:classpath’. 提示错误:Read Time out ...
  • 以下是对JAVA_HOME,CLASSPATH和PATH的作用进行了详细的分析介绍,需要的朋友可以过来参考下
  • 优步快速、超轻量级的 Java 类路径和模块路径扫描器。 通过直接解析类文件二进制格式而不是使用反射来扫描类路径和模块路径。...io.github.lukehutch/fast-classpath-scanner/1.92.0/fast-classpath-scanner-1.92.0.jar
  • NULL 博文链接:https://wangbing9577.iteye.com/blog/2175197
  • 优步快速、超轻量级的 Java 类路径和模块路径扫描器。 通过直接解析类文件二进制格式而不是使用反射来扫描类路径和模块路径。...io.github.lukehutch/fast-classpath-scanner/1.10.2/fast-classpath-scanner-1.10.2.jar
  • 优步快速、超轻量级的 Java 类路径和模块路径扫描器。 通过直接解析类文件二进制格式而不是使用反射来扫描类路径和模块路径。...io.github.lukehutch/fast-classpath-scanner/1.93.3/fast-classpath-scanner-1.93.3.jar
  • 优步快速、超轻量级的 Java 类路径和模块路径扫描器。 通过直接解析类文件二进制格式而不是使用反射来扫描类路径和模块路径。...io.github.lukehutch/fast-classpath-scanner/2.4.2/fast-classpath-scanner-2.4.2.jar
  • javaee-classpath-源码

    2021-05-21 08:46:01
    javaee-classpath 从Slackspace复制
  • 今天小编就为大家分享一篇关于JavaWeb项目中classpath路径详解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
  • 本篇文章主要介绍了Java中-classpath和路径的使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
  • java环环境境变变量量path和和classpath的的配配置置 这篇文章主要为大家详细介绍了java系统环境变量path和classpath的配置过程感兴趣的小伙伴们可以参考一下 在Java的学习 涉及到两个系统环境变量path和classpath ...
  • 本篇文章是对获取JAVA路径,包括CLASSPATH外的路径的方法进行了详细的分析介绍,需要的朋友参考下
  • PAGE / NUMPAGES 怎样配置java环境变量path和classpath及其作用 Path=C:\java\jdk8\bin;C:\java\jdk8\jre\bin; Classpath=;C:\java\jdk8\lib;C:\java\jdk8\jre\lib;C:\java\jdk8\lib\tools.jar;C:\java\jdk8\lib\dt....
  • 主要为大家详细介绍了java系统环境变量path和classpath的配置过程,感兴趣的小伙伴们可以参考一下
  • 自学如何使用框架的工具,项目框架添加classpath文件的
  • classpath备份

    2016-04-24 17:35:29
    classpath备份
  • 本文详细叙述了.classpath中各种属性的含义
  • classpathclasspath*区别

    万次阅读 2019-02-18 18:25:26
    <context:property-placeholder location="classpath*:properties/*.properties" ignore-unresolvable="true"/> <!-- redis 相关配置 --> ${redis.maxIdle}" /> ${redis.maxWait}" /> ${redis.testOnBorrow}" />...

    今天使用redisTemplate,启动时出现Bean创建异常
    bug代码展示:

    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
    	at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
    	at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
    	at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
    	at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
    	at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    	at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    	at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    	at java.lang.Thread.run(Thread.java:745)
    Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.data.redis.core.RedisTemplate com.bajiu.charging.user.service.impl.UserServiceImpl.redisTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisTemplate' defined in URL [jar:file:/D:/develop/Maven_Repository/com/bajiu/charging/charging-utils/1.0-SNAPSHOT/charging-utils-1.0-SNAPSHOT.jar!/spring/applicationContext-redis.xml]: Cannot resolve reference to bean 'JedisConnectionFactory' while setting bean property 'connectionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'JedisConnectionFactory' defined in URL [jar:file:/D:/develop/Maven_Repository/com/bajiu/charging/charging-utils/1.0-SNAPSHOT/charging-utils-1.0-SNAPSHOT.jar!/spring/applicationContext-redis.xml]: Cannot resolve reference to bean 'poolConfig' while setting bean property 'poolConfig'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'poolConfig' defined in URL [jar:file:/D:/develop/Maven_Repository/com/bajiu/charging/charging-utils/1.0-SNAPSHOT/charging-utils-1.0-SNAPSHOT.jar!/spring/applicationContext-redis.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.lang.String] to required type [int] for property 'maxIdle'; nested exception is java.lang.NumberFormatException: For input string: "${redis.maxIdle}"
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
    	at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    	... 22 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisTemplate' defined in URL [jar:file:/D:/develop/Maven_Repository/com/bajiu/charging/charging-utils/1.0-SNAPSHOT/charging-utils-1.0-SNAPSHOT.jar!/spring/applicationContext-redis.xml]: Cannot resolve reference to bean 'JedisConnectionFactory' while setting bean property 'connectionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'JedisConnectionFactory' defined in URL [jar:file:/D:/develop/Maven_Repository/com/bajiu/charging/charging-utils/1.0-SNAPSHOT/charging-utils-1.0-SNAPSHOT.jar!/spring/applicationContext-redis.xml]: Cannot resolve reference to bean 'poolConfig' while setting bean property 'poolConfig'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'poolConfig' defined in URL [jar:file:/D:/develop/Maven_Repository/com/bajiu/charging/charging-utils/1.0-SNAPSHOT/charging-utils-1.0-SNAPSHOT.jar!/spring/applicationContext-redis.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.lang.String] to required type [int] for property 'maxIdle'; nested exception is java.lang.NumberFormatException: For input string: "${redis.maxIdle}"
    	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
    	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1192)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
    	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
    	... 24 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'JedisConnectionFactory' defined in URL [jar:file:/D:/develop/Maven_Repository/com/bajiu/charging/charging-utils/1.0-SNAPSHOT/charging-utils-1.0-SNAPSHOT.jar!/spring/applicationContext-redis.xml]: Cannot resolve reference to bean 'poolConfig' while setting bean property 'poolConfig'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'poolConfig' defined in URL [jar:file:/D:/develop/Maven_Repository/com/bajiu/charging/charging-utils/1.0-SNAPSHOT/charging-utils-1.0-SNAPSHOT.jar!/spring/applicationContext-redis.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.lang.String] to required type [int] for property 'maxIdle'; nested exception is java.lang.NumberFormatException: For input string: "${redis.maxIdle}"
    	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
    	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
    	... 37 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'poolConfig' defined in URL [jar:file:/D:/develop/Maven_Repository/com/bajiu/charging/charging-utils/1.0-SNAPSHOT/charging-utils-1.0-SNAPSHOT.jar!/spring/applicationContext-redis.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.lang.String] to required type [int] for property 'maxIdle'; nested exception is java.lang.NumberFormatException: For input string: "${redis.maxIdle}"
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    	at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
    	... 47 more
    Caused by: org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.lang.String] to required type [int] for property 'maxIdle'; nested exception is java.lang.NumberFormatException: For input string: "${redis.maxIdle}"
    	at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:596)
    	at org.springframework.beans.AbstractNestablePropertyAccessor.convertForProperty(AbstractNestablePropertyAccessor.java:603)
    	at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:204)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1527)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1486)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    	... 53 more
    Caused by: java.lang.NumberFormatException: For input string: "${redis.maxIdle}"
    	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    	at java.lang.Integer.parseInt(Integer.java:569)
    	at java.lang.Integer.valueOf(Integer.java:766)
    	at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:194)
    	at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:113)
    	at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:464)
    	at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:437)
    	at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:195)
    	at org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:576)
    	... 59 more
    
    

    看了看web.xml,没发现问题,最终找到util模块applicationContext-redis.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:cache="http://www.springframework.org/schema/cache"
           xsi:schemaLocation="http://www.springframework.org/schema/beans   
                http://www.springframework.org/schema/beans/spring-beans.xsd   
                http://www.springframework.org/schema/context   
                http://www.springframework.org/schema/context/spring-context.xsd   
                http://www.springframework.org/schema/mvc   
                http://www.springframework.org/schema/mvc/spring-mvc.xsd 
                http://www.springframework.org/schema/cache  
                http://www.springframework.org/schema/cache/spring-cache.xsd">
    
    <!-- 加载redis配置文件 -->
    <!--location="classpath:properties/*.properties"虽然配置文件在本类路径下,依然无法加载 -->
    <context:property-placeholder location="classpath*:properties/*.properties" ignore-unresolvable="true"/>
    <!-- redis 相关配置 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxWaitMillis" value="${redis.maxWait}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>
    
    <bean id="JedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>
    
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="JedisConnectionFactory" />
    </bean>
    
    </beans>  
    

    花了些时间,配置文件的加载redis配置文件出问题了,classpath加载不到本类路径下的redis配置文件,最终用classpath*问题解决了.

    总结:先把各位大佬总结的来
    classpath:只会到你的class路径中查找找文件;
    classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找
    自己稍微深度理解:A–>B–>C 在B中没有配置文件的情况下
    A中classpath* 加载到jar包B中的配置文件,C加载自己配置文件要用classpath* 否则A中加载配置文件无法加载到C中的配置文件

    
    
    
    展开全文
  • 关于springboot中classpath:路径使用说明

    千次阅读 2021-01-26 14:41:06
    使用classpath:做为路径 通过@value获取配置文件中的路径,后经过ResourcePatternResolver 获取文件 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource resource = ...

    1. 案例说明

    resources下有model.conf文件,在配置文件中使用classpath:做为文件路径

    1.1 解决方案

    1.1.1 使用ResourcePatternResolver实现

    使用classpath:做为路径
    通过@value获取配置文件中的路径,后经过ResourcePatternResolver 获取文件

    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource resource = resolver.getResource("classpath:model.conf");
            String path = resource.getFile().getCanonicalPath();
    

    1.1.2 使用 ClassPathResource实现

     ClassPathResource resource = new ClassPathResource("model.conf");
            String path = resource.getFile().getCanonicalPath();
    

    ClassPathResource使用时,文件路径中不存在classpath:

    1.1.3 使用Spring框架中ResourceUtils实现

    File file = ResourceUtils.getFile("classpath:model.conf");
    String path = file.getCanonicalPath();
    

    2. ResourceUtils使用说明

    2.1 源码展示

    /**
     * Utility methods for resolving resource locations to files in the
     * file system. Mainly for internal use within the framework.
     *
     * <p>Consider using Spring's Resource abstraction in the core package
     * for handling all kinds of file resources in a uniform manner.
     * {@link org.springframework.core.io.ResourceLoader}'s {@code getResource()}
     * method can resolve any location to a {@link org.springframework.core.io.Resource}
     * object, which in turn allows one to obtain a {@code java.io.File} in the
     * file system through its {@code getFile()} method.
     *
     * @author Juergen Hoeller
     * @since 1.1.5
     * @see org.springframework.core.io.Resource
     * @see org.springframework.core.io.ClassPathResource
     * @see org.springframework.core.io.FileSystemResource
     * @see org.springframework.core.io.UrlResource
     * @see org.springframework.core.io.ResourceLoader
     */
    public abstract class ResourceUtils {
    
    	/** Pseudo URL prefix for loading from the class path: "classpath:" */
    	public static final String CLASSPATH_URL_PREFIX = "classpath:";
    
    	/** URL prefix for loading from the file system: "file:" */
    	public static final String FILE_URL_PREFIX = "file:";
    
    	/** URL prefix for loading from a jar file: "jar:" */
    	public static final String JAR_URL_PREFIX = "jar:";
    
    	/** URL prefix for loading from a war file on Tomcat: "war:" */
    	public static final String WAR_URL_PREFIX = "war:";
    
    	/** URL protocol for a file in the file system: "file" */
    	public static final String URL_PROTOCOL_FILE = "file";
    
    	/** URL protocol for an entry from a jar file: "jar" */
    	public static final String URL_PROTOCOL_JAR = "jar";
    
    	/** URL protocol for an entry from a war file: "war" */
    	public static final String URL_PROTOCOL_WAR = "war";
    
    	/** URL protocol for an entry from a zip file: "zip" */
    	public static final String URL_PROTOCOL_ZIP = "zip";
    
    	/** URL protocol for an entry from a WebSphere jar file: "wsjar" */
    	public static final String URL_PROTOCOL_WSJAR = "wsjar";
    
    	/** URL protocol for an entry from a JBoss jar file: "vfszip" */
    	public static final String URL_PROTOCOL_VFSZIP = "vfszip";
    
    	/** URL protocol for a JBoss file system resource: "vfsfile" */
    	public static final String URL_PROTOCOL_VFSFILE = "vfsfile";
    
    	/** URL protocol for a general JBoss VFS resource: "vfs" */
    	public static final String URL_PROTOCOL_VFS = "vfs";
    
    	/** File extension for a regular jar file: ".jar" */
    	public static final String JAR_FILE_EXTENSION = ".jar";
    
    	/** Separator between JAR URL and file path within the JAR: "!/" */
    	public static final String JAR_URL_SEPARATOR = "!/";
    
    	/** Special separator between WAR URL and jar part on Tomcat */
    	public static final String WAR_URL_SEPARATOR = "*/";
    
    
    	/**
    	 * Return whether the given resource location is a URL:
    	 * either a special "classpath" pseudo URL or a standard URL.
    	 * @param resourceLocation the location String to check
    	 * @return whether the location qualifies as a URL
    	 * @see #CLASSPATH_URL_PREFIX
    	 * @see java.net.URL
    	 */
    	public static boolean isUrl(@Nullable String resourceLocation) {
    		if (resourceLocation == null) {
    			return false;
    		}
    		if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
    			return true;
    		}
    		try {
    			new URL(resourceLocation);
    			return true;
    		}
    		catch (MalformedURLException ex) {
    			return false;
    		}
    	}
    
    	/**
    	 * Resolve the given resource location to a {@code java.net.URL}.
    	 * <p>Does not check whether the URL actually exists; simply returns
    	 * the URL that the given location would correspond to.
    	 * @param resourceLocation the resource location to resolve: either a
    	 * "classpath:" pseudo URL, a "file:" URL, or a plain file path
    	 * @return a corresponding URL object
    	 * @throws FileNotFoundException if the resource cannot be resolved to a URL
    	 */
    	public static URL getURL(String resourceLocation) throws FileNotFoundException {
    		Assert.notNull(resourceLocation, "Resource location must not be null");
    		if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
    			String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
    			ClassLoader cl = ClassUtils.getDefaultClassLoader();
    			URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path));
    			if (url == null) {
    				String description = "class path resource [" + path + "]";
    				throw new FileNotFoundException(description +
    						" cannot be resolved to URL because it does not exist");
    			}
    			return url;
    		}
    		try {
    			// try URL
    			return new URL(resourceLocation);
    		}
    		catch (MalformedURLException ex) {
    			// no URL -> treat as file path
    			try {
    				return new File(resourceLocation).toURI().toURL();
    			}
    			catch (MalformedURLException ex2) {
    				throw new FileNotFoundException("Resource location [" + resourceLocation +
    						"] is neither a URL not a well-formed file path");
    			}
    		}
    	}
    
    	/**
    	 * Resolve the given resource location to a {@code java.io.File},
    	 * i.e. to a file in the file system.
    	 * <p>Does not check whether the file actually exists; simply returns
    	 * the File that the given location would correspond to.
    	 * @param resourceLocation the resource location to resolve: either a
    	 * "classpath:" pseudo URL, a "file:" URL, or a plain file path
    	 * @return a corresponding File object
    	 * @throws FileNotFoundException if the resource cannot be resolved to
    	 * a file in the file system
    	 */
    	public static File getFile(String resourceLocation) throws FileNotFoundException {
    		Assert.notNull(resourceLocation, "Resource location must not be null");
    		if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
    			String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
    			String description = "class path resource [" + path + "]";
    			ClassLoader cl = ClassUtils.getDefaultClassLoader();
    			URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path));
    			if (url == null) {
    				throw new FileNotFoundException(description +
    						" cannot be resolved to absolute file path because it does not exist");
    			}
    			return getFile(url, description);
    		}
    		try {
    			// try URL
    			return getFile(new URL(resourceLocation));
    		}
    		catch (MalformedURLException ex) {
    			// no URL -> treat as file path
    			return new File(resourceLocation);
    		}
    	}
    
    	/**
    	 * Resolve the given resource URL to a {@code java.io.File},
    	 * i.e. to a file in the file system.
    	 * @param resourceUrl the resource URL to resolve
    	 * @return a corresponding File object
    	 * @throws FileNotFoundException if the URL cannot be resolved to
    	 * a file in the file system
    	 */
    	public static File getFile(URL resourceUrl) throws FileNotFoundException {
    		return getFile(resourceUrl, "URL");
    	}
    
    	/**
    	 * Resolve the given resource URL to a {@code java.io.File},
    	 * i.e. to a file in the file system.
    	 * @param resourceUrl the resource URL to resolve
    	 * @param description a description of the original resource that
    	 * the URL was created for (for example, a class path location)
    	 * @return a corresponding File object
    	 * @throws FileNotFoundException if the URL cannot be resolved to
    	 * a file in the file system
    	 */
    	public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
    		Assert.notNull(resourceUrl, "Resource URL must not be null");
    		if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {
    			throw new FileNotFoundException(
    					description + " cannot be resolved to absolute file path " +
    					"because it does not reside in the file system: " + resourceUrl);
    		}
    		try {
    			return new File(toURI(resourceUrl).getSchemeSpecificPart());
    		}
    		catch (URISyntaxException ex) {
    			// Fallback for URLs that are not valid URIs (should hardly ever happen).
    			return new File(resourceUrl.getFile());
    		}
    	}
    
    	/**
    	 * Resolve the given resource URI to a {@code java.io.File},
    	 * i.e. to a file in the file system.
    	 * @param resourceUri the resource URI to resolve
    	 * @return a corresponding File object
    	 * @throws FileNotFoundException if the URL cannot be resolved to
    	 * a file in the file system
    	 * @since 2.5
    	 */
    	public static File getFile(URI resourceUri) throws FileNotFoundException {
    		return getFile(resourceUri, "URI");
    	}
    
    	/**
    	 * Resolve the given resource URI to a {@code java.io.File},
    	 * i.e. to a file in the file system.
    	 * @param resourceUri the resource URI to resolve
    	 * @param description a description of the original resource that
    	 * the URI was created for (for example, a class path location)
    	 * @return a corresponding File object
    	 * @throws FileNotFoundException if the URL cannot be resolved to
    	 * a file in the file system
    	 * @since 2.5
    	 */
    	public static File getFile(URI resourceUri, String description) throws FileNotFoundException {
    		Assert.notNull(resourceUri, "Resource URI must not be null");
    		if (!URL_PROTOCOL_FILE.equals(resourceUri.getScheme())) {
    			throw new FileNotFoundException(
    					description + " cannot be resolved to absolute file path " +
    					"because it does not reside in the file system: " + resourceUri);
    		}
    		return new File(resourceUri.getSchemeSpecificPart());
    	}
    
    	/**
    	 * Determine whether the given URL points to a resource in the file system,
    	 * i.e. has protocol "file", "vfsfile" or "vfs".
    	 * @param url the URL to check
    	 * @return whether the URL has been identified as a file system URL
    	 */
    	public static boolean isFileURL(URL url) {
    		String protocol = url.getProtocol();
    		return (URL_PROTOCOL_FILE.equals(protocol) || URL_PROTOCOL_VFSFILE.equals(protocol) ||
    				URL_PROTOCOL_VFS.equals(protocol));
    	}
    
    	/**
    	 * Determine whether the given URL points to a resource in a jar file.
    	 * i.e. has protocol "jar", "war, ""zip", "vfszip" or "wsjar".
    	 * @param url the URL to check
    	 * @return whether the URL has been identified as a JAR URL
    	 */
    	public static boolean isJarURL(URL url) {
    		String protocol = url.getProtocol();
    		return (URL_PROTOCOL_JAR.equals(protocol) || URL_PROTOCOL_WAR.equals(protocol) ||
    				URL_PROTOCOL_ZIP.equals(protocol) || URL_PROTOCOL_VFSZIP.equals(protocol) ||
    				URL_PROTOCOL_WSJAR.equals(protocol));
    	}
    
    	/**
    	 * Determine whether the given URL points to a jar file itself,
    	 * that is, has protocol "file" and ends with the ".jar" extension.
    	 * @param url the URL to check
    	 * @return whether the URL has been identified as a JAR file URL
    	 * @since 4.1
    	 */
    	public static boolean isJarFileURL(URL url) {
    		return (URL_PROTOCOL_FILE.equals(url.getProtocol()) &&
    				url.getPath().toLowerCase().endsWith(JAR_FILE_EXTENSION));
    	}
    
    	/**
    	 * Extract the URL for the actual jar file from the given URL
    	 * (which may point to a resource in a jar file or to a jar file itself).
    	 * @param jarUrl the original URL
    	 * @return the URL for the actual jar file
    	 * @throws MalformedURLException if no valid jar file URL could be extracted
    	 */
    	public static URL extractJarFileURL(URL jarUrl) throws MalformedURLException {
    		String urlFile = jarUrl.getFile();
    		int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);
    		if (separatorIndex != -1) {
    			String jarFile = urlFile.substring(0, separatorIndex);
    			try {
    				return new URL(jarFile);
    			}
    			catch (MalformedURLException ex) {
    				// Probably no protocol in original jar URL, like "jar:C:/mypath/myjar.jar".
    				// This usually indicates that the jar file resides in the file system.
    				if (!jarFile.startsWith("/")) {
    					jarFile = "/" + jarFile;
    				}
    				return new URL(FILE_URL_PREFIX + jarFile);
    			}
    		}
    		else {
    			return jarUrl;
    		}
    	}
    
    	/**
    	 * Extract the URL for the outermost archive from the given jar/war URL
    	 * (which may point to a resource in a jar file or to a jar file itself).
    	 * <p>In the case of a jar file nested within a war file, this will return
    	 * a URL to the war file since that is the one resolvable in the file system.
    	 * @param jarUrl the original URL
    	 * @return the URL for the actual jar file
    	 * @throws MalformedURLException if no valid jar file URL could be extracted
    	 * @since 4.1.8
    	 * @see #extractJarFileURL(URL)
    	 */
    	public static URL extractArchiveURL(URL jarUrl) throws MalformedURLException {
    		String urlFile = jarUrl.getFile();
    
    		int endIndex = urlFile.indexOf(WAR_URL_SEPARATOR);
    		if (endIndex != -1) {
    			// Tomcat's "war:file:...mywar.war*/WEB-INF/lib/myjar.jar!/myentry.txt"
    			String warFile = urlFile.substring(0, endIndex);
    			if (URL_PROTOCOL_WAR.equals(jarUrl.getProtocol())) {
    				return new URL(warFile);
    			}
    			int startIndex = warFile.indexOf(WAR_URL_PREFIX);
    			if (startIndex != -1) {
    				return new URL(warFile.substring(startIndex + WAR_URL_PREFIX.length()));
    			}
    		}
    
    		// Regular "jar:file:...myjar.jar!/myentry.txt"
    		return extractJarFileURL(jarUrl);
    	}
    
    	/**
    	 * Create a URI instance for the given URL,
    	 * replacing spaces with "%20" URI encoding first.
    	 * @param url the URL to convert into a URI instance
    	 * @return the URI instance
    	 * @throws URISyntaxException if the URL wasn't a valid URI
    	 * @see java.net.URL#toURI()
    	 */
    	public static URI toURI(URL url) throws URISyntaxException {
    		return toURI(url.toString());
    	}
    
    	/**
    	 * Create a URI instance for the given location String,
    	 * replacing spaces with "%20" URI encoding first.
    	 * @param location the location String to convert into a URI instance
    	 * @return the URI instance
    	 * @throws URISyntaxException if the location wasn't a valid URI
    	 */
    	public static URI toURI(String location) throws URISyntaxException {
    		return new URI(StringUtils.replace(location, " ", "%20"));
    	}
    
    	/**
    	 * Set the {@link URLConnection#setUseCaches "useCaches"} flag on the
    	 * given connection, preferring {@code false} but leaving the
    	 * flag at {@code true} for JNLP based resources.
    	 * @param con the URLConnection to set the flag on
    	 */
    	public static void useCachesIfNecessary(URLConnection con) {
    		con.setUseCaches(con.getClass().getSimpleName().startsWith("JNLP"));
    	}
    
    }
    
    

    2.2 常用方法

    2.2.1 extractJarFileURL

    public static URL extractJarFileURL(URL jarUrl)

    从给定的URL (URL可以指向jar文件中的资源或jar文件本身)中提取实际jar文件的URL

    2.2.2 getFile

    • getFile(String resourceLocation):将给定的资源位置解析为java.io.file
    • getFile(URI resourceUri) :将给定的资源位置解析为java.io.file
    • getFile(String resourceLocation) :将给定的资源位置解析为java.io.file
    • getFile(URL resourceUrl, String description) :将给定的资源位置解析为java.io.file
    • getFile(URL resourceUrl, String description) :将给定的资源位置解析为java.io.file

    2.2.3 getURL

    getURL(String resourceLocation)

    将给定的资源位置解析为java.net.URL

    2.2.4 isJarURL

    isJarURL(URL url)

    确定给定的URL是否指向jar文件中的资源,即具有协议“jar”、“zip”、“wsjar”或“代码源”

    2.2.5 isUrl

    返回给定资源位置是否是URL:一个特殊的“classpath”伪URL还是一个标准URL。

    2.2.6 toURI

    • toURI(String location) :为给定的URL创建一个URI实例,首先用“%20”引号替换空格。
    • toURI(URL url) :为给定的URL创建一个URI实例,首先用“%20”引号替换空格。

    3. 常见问题

    3.1 打成jar后获取不到文件

    Resource下的文件是存在于jar这个文件里面,在磁盘上是没有真实路径存在的,它是位于jar内部的一个路径。所以通过ResourceUtils.getFile或者this.getClass().getResource("")方法无法正确获取文件。
    解决方案:

    BufferedReader in = new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(path)));
    StringBuffer buffer = new StringBuffer();
    String line = "";
    while ((line = in.readLine()) != null){
        buffer.append(line);
    }
    String input = buffer.toString();
    
    展开全文
  • 关于classpath: classpath*,

    千次阅读 2018-11-01 19:34:42
    然后classpath:resources即可,或者是针对如果和src和config一个路径下, 现在   如果是针对src 下面 2 IDEA maven 下面 src/main/java src/main/resources classpath 就是针对src/main/java或者是sr.....

    eclipse 中:

    1 在src目录下建个resources文件夹,丢配置文件.然后classpath:resources即可,或者是针对如果和src和config一个路径下,

    现在

     

    如果是针对src 下面

    2 IDEA maven 下面

    src/main/java

    src/main/resources

    classpath 就是针对src/main/java或者是src/main/resources  下面都是classpath 下面

     

     

    其他:

    1. classpath:/xxx 和 classpath:xxx是一样的

    classpath:xxx 和 classpath*:xxx是不一样的,前者表示引入一个,后者表示引入多个。

    其实我经常喜欢回答群里人问的问题,可能很多大神完全不屑于回答。但是对我这菜鸟来说,能在解答的过程中重新学习认识一遍。是一种很有效的学习/复习方法。而且从他人的代码/问题中能学习到很多我所没遇到的问题和知识。

     

    classpath : 指的是打成war包以后的web-info 文件夹下面的classes 文件夹里面的路径

    这种情况下打成war包的话

     

    这种情况下获取的时候<param-value>classpath:springmvc/NewFile.xml</param-value>

    springmvc 是包名称

    javaWeb项目的classpath说明

     classpath 路径在每个J2ee项目中都会用到,即WEB-INF下面的classes目录,所有src目录下面的java、xml、properties等文件编译后都会在此,所以在开发时常将相应的xml配置文件放于src或其子目录下;

              引用classpath路径下的文件,只需在文件名前加classpath:(需保证该文件确实位于classpath路径下);

    如:

    1

    <param-value>classpath:applicationContext-*.xml</param-value

      或者引用其子目录下的文件,如  

    1

    <param-value>classpath:context/conf/controller.xml</param-value>

       classpath* 的使用:当项目中有多个classpath路径,并同时加载多个classpath路径下(此种情况多数不会遇到)的文件,*就发挥了作用,如果不加*,则表示仅仅加载第一个classpath路径,代码片段: 

    1

    <param-value>classpath*:context/conf/controller*.xml</param-value>

      

     ########################################################

    首先  classpath是指 WEB-INF文件夹下的classes目录 
    解释classes含义: 

    1. 存放各种资源配置文件 eg.init.properties log4j.properties struts.xml 
    2. 存放模板文件         eg.actionerror.ftl 
    3. 存放class文件       对应的是项目开发时的src目录编译文件 

    总结:这是一个定位资源的入口 

    如果你知道开发过程中有这么一句话:惯例大于配置 那么也许你会改变你的想法 
    对于第二个问题  
    这个涉及的是lib和classes下文件访问优先级的问题:  lib>classes 
    对于性能的影响应该不在这个范畴 

     ########################################################

    知乎上网友的问题:(转载)

    坑爹的javaWeb项目路径问题(classpath /WEB-INF...)?

        目前还没完全搞懂
        只知道把配置文件如:struts.xml、applicationContext.xml等放到src目录(就是存放代码.java文件的目录),然后使用“classpath:xxx.xml”来读取,都放到src目录准没错
        曾经试过把配置文件放到WEB-INF目录,然后以路径“/WEB-INF/xxxx.xml”来成功读取配置文件
    但是在用ClassPathXmlApplicationContext()函数不能读取这样的路径,用上面的方法(用“classpath:xxx.xml”来读取)才能成功读取配置文件

    回答:

    【01】 src路径下的文件在编译后会放到WEB-INF/clases路径下吧。默认的classpath是在这里。直接放到WEB-INF下的话,是不在classpath下的。用ClassPathXmlApplicationContext当然获取不到。

    【02】 如果单元测试的话,可以在启动或者运行的选项里指定classpath的路径的。用maven构建项目时候resource目录就是默认的classpath

    【03】 classPath即为java文件编译之后的class文件的编译目录一般为web-inf/classes,src下的xml在编译时也会复制到classPath下

    String path="WebContent/WEB-INF/KmssConfig/szcmb/kemorgiText/spring.xml"; ApplicationContext context = new FileSystemXmlApplicationContext(path);

     

    在web-inf 下面的东西没有在web-inf/classes/路径下,所以不能采用

     

     

    (2)ApplicationContext ctx = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/xxxx.xml");   //读取WEB-INF 下的spring.xml文件

     ########################################################

    web.xml 配置中classpath: 与classpath*:的区别

    首先 classpath是指 WEB-INF文件夹下的classes目录 
    解释classes含义: 
    1.存放各种资源配置文件 eg.init.properties log4j.properties struts.xml 
    2.存放模板文件 eg.actionerror.ftl 
    3.存放class文件 对应的是项目开发时的src目录编译文件 
    总结:这是一个定位资源的入口 

    如果你知道开发过程中有这么一句话:惯例大于配置 那么也许你会改变你的想法 

    对于第二个问题 
    这个涉及的是lib和classes下文件访问优先级的问题: lib>classes 
    对于性能的影响应该不在这个范畴 

    classpath 和 classpath* 区别: 
    classpath:只会到你的class路径中查找找文件; 
    classpath*:不仅包含class路径,还包括jar文件中(class路径)进行查找. 

    1

    <param-value>classpath:applicationContext-*.xml</param-value>

      或者引用其子目录下的文件,如 

    1

    <param-value>classpath:context/conf/controller.xml</param-value>

      classpath*的使用:当项目中有多个classpath路径,并同时加载多个classpath路径下(此种情况多数不会遇到)的文件,*就发挥了作用,如果不加*,则表示仅仅加载第一个classpath路径,代码片段:

    1

    <param-value>classpath*:context/conf/controller*.xml</param-value>

      另外: 
       "**/" 表示的是任意目录; 
       "**/applicationContext-*.xml"  表示任意目录下的以"applicationContext-"开头的XML文件。  
       程序部署到tomcat后,src目录下的配置文件会和class文件一样,自动copy到应用的 WEB-INF/classes目录下 
       classpath:与classpath*:的区别在于, 

       前者只会从第一个classpath中加载,而 
       后者会从所有的classpath中加载  

       如果要加载的资源, 不在当前ClassLoader的路径里,那么用classpath:前缀是找不到的, 这种情况下就需要使用classpath*:前缀 

       在多个classpath中存在同名资源,都需要加载,  那么用classpath:只会加载第一个,这种情况下也需要用classpath*:前缀 

       注意: 
       用classpath*:需要遍历所有的classpath,所以加载速度是很慢的,因此,在规划的时候,应该尽可能规划好资源文件所在的路径,尽量避免使用 classpath* 

     三 实例解析

    写的一个小项目

       下边是它对应的webapps中的路径:

    两个一对比,一目了然...

    从这里看的: javaWeb项目的classpath说明,感觉总结的很好.  另外如果你遇到这个问题:Eclipse启动Web项目 Tomcat中webapps中没有项目文件夹 ,可以参考这个,很6666.

       看了看真的是好久没有更新博客了,现在也开始上班了,发现玩的时间太长了,好多东西都忘了...................

     

     


    如果您觉得阅读本文对您有帮助,请点一下�?推荐”按钮,您的“推荐�?将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利�?

    分类: JavaWeb

    好文要顶 关注我 收藏该文

    超超boy
    关注 - 20
    粉丝 - 70

    +加关注

    1

    0

    « 上一篇:mysql5.7 设置远程访问
    » 下一篇:异常笔记--java编程思想

    posted @ 2017-08-12 10:24 超超boy 阅读(12834) 评论(0) 编辑 收藏

     

    展开全文

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 689,877
精华内容 275,950
关键字:

classpath