classpath

classpath 概念及使用

classpath 是 java web 项目编译后 class 所在的目录,一般为:root/WEB-INF/classes

在 web.xml 中经常用到 classpath 来定位配置文件,例如 springmvc 的配置:

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
       <!-- <param-value>src/main/resources/springmvc.xml</param-value> -->
    </init-param>
</servlet>

在 pom.xml 里面是不能使用 classpath 的。

对于一个 maven 工程,目录结构大致是这样的:

src
  main
    java
    resources
      *.xml
      *.properties
    webapp
      *.jsp
      WEB-INF
        web.xml
  test

对应打包后的目录:

root
  *.jsp
  WEB-INF
    classes
      *.class
      *.xml
      *.properties
    lib
    web.xml

webapp 目录下的文件被放到了根目录下,这样在 url 中可以直接定位 jsp。

编译后的 java 和 resources 下的文件都被放到了 WEB-INF/classes 文件夹下面,这个路径就是 classpath。

因此只要配置文件都放在了 resources 文件夹下,就能根据 classpath 就能相对定位到配置文件。

对于 maven,可在 pom.xml 中指定要加载的资源文件:

<resources>
	<resource>
		<directory>src/main/java</directory>
		<includes>
			<include>**/*.properties</include>
			<include>**/*.xml</include>
		</includes>
		<filtering>false</filtering>
	</resource>
	<resource>
		<directory>src/main/resources</directory>
		<includes>
			<include>**/*.properties</include>
			<include>**/*.xml</include>
		</includes>
		<filtering>false</filtering>
	</resource>    	
</resources>

对于 eclipse,也可在项目的 build path 中指定:
在这里插入图片描述

利用 ClassLoader 读取配置文件内容

读取 properties 文件:

ClassLoader classLoader = Test.class.getClassLoader();
Properties properties = new Properties();
InputStream inputStream = classLoader.getResourceAsStream("jdbc.properties");
properties.load(inputStream);
String jdbcUrl = (String) properties.get("jdbc.jdbcUrl");
System.out.println(jdbcUrl);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值