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);