在java开发中,properties文件是最常用的配置文件格式之一,其以
key=value的键值对结构存储配置信息(如数据库连接参数、接口地址、系统开关等),具有简洁易维护、解耦配置与代码的核心优势。不同场景下(如普通java项目、spring项目、web应用、java 9+模块化项目),properties文件的加载方式存在差异。本文将详细拆解六种主流加载方式,包含适用场景、实现步骤、代码示例、优缺点及最佳实践,帮助开发者灵活应对各类配置加载需求。
一、核心前提:properties文件基础
1. 文件格式与规范
- 后缀名:
.properties(默认)或.config(自定义) - 编码:默认
iso-8859-1(不支持中文),推荐显式指定utf-8 - 内容格式:
key=value(等号可替换为:),注释以#或!开头 - 示例(
config.properties):
# 数据库配置 db.url=jdbc:mysql://localhost:3306/test db.username=root db.password=123456 # 系统配置(中文需utf-8编码) system.name=测试系统
2. 核心api
java通过java.util.properties类操作properties文件,核心方法:
load(inputstream instream):从字节流加载配置(默认iso-8859-1编码)load(reader reader):从字符流加载配置(支持指定编码,如utf-8)getproperty(string key):获取指定key的value(无值时返回null)getproperty(string key, string defaultvalue):获取value,无值时返回默认值
二、六种加载方式详解
方式一:classloader.getresourceasstream()(类路径加载,最常用)
适用场景
- 普通java项目、spring boot项目
- 配置文件放在
classpath下(如src/main/resources目录) - 需跨环境(开发/测试/生产)移植,无需关心文件系统绝对路径
核心原理
通过类加载器(classloader)读取classpath下的资源文件,路径以classpath根目录为基准,无需写绝对路径,支持打包后(jar/war)的资源加载。
实现步骤与代码示例
- 配置文件位置:
src/main/resources/config.properties(maven/gradle项目标准目录) - 加载代码(支持三种classloader获取方式):
import java.io.ioexception;
import java.io.inputstreamreader;
import java.nio.charset.standardcharsets;
import java.util.properties;
public class propertiesloader1 {
public static void main(string[] args) {
properties props = new properties();
// 方式1:当前类的classloader(推荐,避免线程上下文类加载器问题)
try (inputstreamreader isr = new inputstreamreader(
propertiesloader1.class.getclassloader().getresourceasstream("config.properties"),
standardcharsets.utf_8)) { // 显式指定utf-8编码,解决中文乱码
props.load(isr);
} catch (ioexception e) {
throw new runtimeexception("加载配置文件失败", e);
}
// 方式2:thread上下文类加载器(适用于多线程/框架场景)
/*try (inputstreamreader isr = new inputstreamreader(
thread.currentthread().getcontextclassloader().getresourceasstream("config.properties"),
standardcharsets.utf_8)) {
props.load(isr);
} catch (ioexception e) {
throw new runtimeexception("加载配置文件失败", e);
}*/
// 方式3:系统类加载器(与方式1效果一致,不推荐)
/*try (inputstreamreader isr = new inputstreamreader(
classloader.getsystemclassloader().getresourceasstream("config.properties"),
standardcharsets.utf_8)) {
props.load(isr);
} catch (ioexception e) {
throw new runtimeexception("加载配置文件失败", e);
}*/
// 读取配置
system.out.println("数据库url:" + props.getproperty("db.url"));
system.out.println("系统名称:" + props.getproperty("system.name")); // 中文正常显示
}
}路径规则
- 相对路径:直接写文件名(如
"config.properties"),默认从classpath根目录查找 - 子目录:若文件在
src/main/resources/config/db.properties,路径为"config/db.properties" - 禁止写绝对路径(如
"d:/config.properties"),类加载器仅识别classpath下的资源
优缺点
- 优点:跨环境移植性强、支持jar包内资源、无需关心文件系统路径
- 缺点:仅能加载
classpath下的文件,无法加载外部文件系统的配置
方式二:fileinputstream(文件系统路径加载)
适用场景
- 配置文件放在项目外部(如服务器特定目录、用户目录)
- 需动态指定配置文件路径(如通过命令行参数传入)
- 非
classpath下的本地文件加载
核心原理
通过文件系统的绝对路径或相对路径,直接读取文件字节流,依赖操作系统的文件系统接口。
实现步骤与代码示例
- 配置文件位置:
d:/config/config.properties(绝对路径)或./config.properties(项目根目录相对路径) - 加载代码:
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.nio.charset.standardcharsets;
import java.util.properties;
public class propertiesloader2 {
public static void main(string[] args) {
properties props = new properties();
string filepath;
// 方式1:绝对路径(windows/dinux通用,linux路径如"/opt/config/config.properties")
filepath = "d:/config/config.properties";
// 方式2:相对路径(基准目录为项目根目录,如idea中为项目文件夹)
// filepath = "./config.properties";
// 方式3:命令行参数传入路径(灵活适配不同环境)
// if (args.length > 0) filepath = args[0];
try (inputstreamreader isr = new inputstreamreader(
new fileinputstream(filepath),
standardcharsets.utf_8)) { // 指定utf-8编码
props.load(isr);
} catch (ioexception e) {
throw new runtimeexception("加载配置文件失败,路径:" + filepath, e);
}
// 读取配置
system.out.println("数据库用户名:" + props.getproperty("db.username"));
system.out.println("数据库密码:" + props.getproperty("db.password"));
}
}路径规则
- 绝对路径:包含完整的盘符(windows)或根目录(linux),如
"d:/config.properties"、"/opt/config.properties" - 相对路径:以当前工作目录为基准(idea中为项目根目录,jar运行时为启动命令所在目录),如
"./conf/config.properties"(项目根目录下的conf文件夹) - 注意:相对路径的基准目录可能因运行环境变化(如ide、脚本启动、容器部署),需谨慎使用
优缺点
- 优点:可加载任意位置的文件、路径灵活配置
- 缺点:移植性差(路径依赖操作系统)、需手动处理路径正确性、打包后无法加载jar内的资源
方式三:spring框架加载(@propertysource + @value)
适用场景
- spring framework、spring boot项目
- 需集成spring的依赖注入(di),自动注入配置属性
- 支持多配置文件加载、占位符解析、配置优先级管理
核心原理
spring通过@propertysource注解指定配置文件路径,由propertysourcesplaceholderconfigurer自动加载配置,结合@value注解注入属性,支持classpath、文件系统路径、url等多种资源。
实现步骤与代码示例
1. 普通spring项目(xml配置)
<!-- applicationcontext.xml -->
<context:component-scan base-package="com.example"/>
<context:property-placeholder
location="classpath:config.properties,file:d:/config/ext-config.properties"
file-encoding="utf-8"/> <!-- 支持多文件、混合路径、指定编码 -->import org.springframework.beans.factory.annotation.value;
import org.springframework.stereotype.component;
@component
public class springconfigloader {
// 注入配置属性,支持默认值
@value("${db.url}")
private string dburl;
@value("${db.username}")
private string dbusername;
@value("${system.name:默认系统}") // 无该key时返回默认值
private string systemname;
// 测试方法
public void printconfig() {
system.out.println("spring加载 - 数据库url:" + dburl);
system.out.println("spring加载 - 系统名称:" + systemname);
}
}2. spring boot项目(注解驱动)
spring boot默认加载classpath:application.properties/application.yml,若需加载自定义文件,使用@propertysource:
import org.springframework.beans.factory.annotation.value;
import org.springframework.context.annotation.configuration;
import org.springframework.context.annotation.propertysource;
// 加载classpath下的config.properties和外部文件
@configuration
@propertysource(value = {
"classpath:config.properties",
"file:d:/config/ext-config.properties"
}, encoding = "utf-8") // 指定utf-8编码(spring 4.3+支持)
public class bootconfigloader {
@value("${db.url}")
private string dburl;
@value("${db.password}")
private string dbpassword;
@value("${system.version:1.0.0}")
private string systemversion;
// 提供getter方法供业务使用
public string getdburl() {
return dburl;
}
public string getdbpassword() {
return dbpassword;
}
}3. spring boot 2.4+ 推荐方式(application.properties指定额外配置)
# application.properties spring.config.import=classpath:config.properties,file:d:/config/ext-config.properties
路径规则
classpath:前缀:加载classpath下的文件(如classpath:config.properties)file:前缀:加载文件系统路径(如file:d:/config.properties)- 无前缀:默认按
classpath查找 - 支持url路径:如
https://config.example.com/config.properties(需网络可达)
优缺点
- 优点:集成spring生态、支持依赖注入、自动解析占位符、多文件加载、配置优先级管理
- 缺点:依赖spring框架、非spring项目无法使用
方式四:java 9+ module资源加载(module.getresourceasstream())
适用场景
- java 9及以上模块化项目(使用
module-info.java) - 需遵循模块的资源访问控制(避免非模块访问模块内资源)
- 模块化打包(jmod/jar)后的资源加载
核心原理
java 9引入模块系统(module system)后,传统classloader加载资源可能受模块权限限制,需通过module接口的getresourceasstream()方法加载模块内的资源,支持模块间的资源访问控制。
实现步骤与代码示例
- 模块化项目结构:
src/ ├── main/ │ ├── java/ │ │ ├── com/ │ │ │ └── example/ │ │ │ └── moduleconfigloader.java │ │ └── module-info.java │ └── resources/ │ └── config.properties
module-info.java配置(关键:开放资源访问权限):
// 模块名:com.example.config
module com.example.config {
// 允许其他模块访问本模块的资源(可选,若仅内部使用可省略)
opens com.example to java.base;
// 导出包(若需外部模块使用加载类)
exports com.example;
}
- 加载代码:
package com.example;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.nio.charset.standardcharsets;
import java.util.properties;
public class moduleconfigloader {
public static void main(string[] args) {
properties props = new properties();
// 方式1:通过当前类的module加载(推荐)
try (inputstreamreader isr = new inputstreamreader(
moduleconfigloader.class.getmodule().getresourceasstream("config.properties"),
standardcharsets.utf_8)) {
props.load(isr);
} catch (ioexception e) {
throw new runtimeexception("模块内加载配置文件失败", e);
}
// 方式2:通过模块名获取module(需模块已加载)
/*module module = modulelayer.boot().findmodule("com.example.config").orelsethrow();
try (inputstreamreader isr = new inputstreamreader(
module.getresourceasstream("config.properties"),
standardcharsets.utf_8)) {
props.load(isr);
} catch (ioexception e) {
throw new runtimeexception("加载模块资源失败", e);
}*/
// 读取配置
system.out.println("模块加载 - 数据库url:" + props.getproperty("db.url"));
system.out.println("模块加载 - 系统名称:" + props.getproperty("system.name"));
}
}关键注意事项
- 模块内资源默认仅允许模块内部访问,若需外部模块访问,需在
module-info.java中通过opens语句开放资源所在包 - 资源路径以模块的
classpath为基准,与传统类加载器路径规则一致 - 避免使用
classloader加载模块化项目的资源,可能因模块权限限制失败
优缺点
- 优点:符合java模块化规范、资源访问可控、支持模块化打包
- 缺点:仅支持java 9+、需额外配置
module-info.java、非模块化项目无法使用
方式五:apache commons configuration(第三方库加载)
适用场景
- 需简化加载逻辑(无需手动处理流、编码)
- 支持多种配置格式(properties、xml、json等)
- 需高级特性(配置刷新、变量插值、多文件合并)
核心原理
apache commons configuration是apache开源项目,提供了更强大的配置加载api,封装了流处理、编码转换、异常处理等细节,支持classpath、文件系统、url等多种资源。
实现步骤与代码示例
- 引入依赖(maven):
<!-- apache commons configuration 2.x -->
<dependency>
<groupid>org.apache.commons</groupid>
<artifactid>commons-configuration2</artifactid>
<version>2.10.1</version>
</dependency>
<!-- 依赖 commons lang 和 commons collections -->
<dependency>
<groupid>org.apache.commons</groupid>
<artifactid>commons-lang3</artifactid>
<version>3.14.0</version>
</dependency>- 加载代码:
import org.apache.commons.configuration2.propertiesconfiguration;
import org.apache.commons.configuration2.ex.configurationexception;
public class commonsconfigloader {
public static void main(string[] args) {
propertiesconfiguration config;
try {
// 方式1:加载classpath下的文件
config = new propertiesconfiguration("config.properties");
// 方式2:加载文件系统路径
// config = new propertiesconfiguration("d:/config/config.properties");
// 方式3:指定编码(默认utf-8,无需额外处理中文)
// config = new propertiesconfiguration();
// config.setencoding("utf-8");
// config.load("classpath:config.properties");
} catch (configurationexception e) {
throw new runtimeexception("加载配置文件失败", e);
}
// 读取配置(支持默认值、类型转换)
string dburl = config.getstring("db.url");
string dbusername = config.getstring("db.username");
string systemname = config.getstring("system.name", "默认系统"); // 默认值
int dbport = config.getint("db.port", 3306); // 类型转换+默认值
system.out.println("commons加载 - 数据库url:" + dburl);
system.out.println("commons加载 - 数据库端口:" + dbport);
system.out.println("commons加载 - 系统名称:" + systemname);
}
}核心特性
- 自动处理编码(默认utf-8),无需手动创建
inputstreamreader - 支持类型转换(
getint、getboolean等) - 支持配置刷新(
config.refresh()) - 支持多文件合并(
compositeconfiguration) - 支持变量插值(如
key=${other.key})
优缺点
- 优点:api简洁、功能强大、支持多种格式、无需手动处理流
- 缺点:需引入第三方依赖、增加项目体积
方式六:servletcontext.getresourceasstream()(web应用专属)
适用场景
- java web应用(servlet、jsp、ssm等)
- 配置文件放在
web-inf目录下(安全,不允许客户端直接访问) - 需通过servlet上下文加载web应用内的资源
核心原理
web应用启动时,servlet容器(tomcat、jetty)会创建servletcontext(servlet上下文),通过其getresourceasstream()方法可加载web应用目录下的资源,路径以/开头,基准目录为web应用根目录(web-inf的上级目录)。
实现步骤与代码示例
- 配置文件位置:
web-inf/config/config.properties(web应用目录) - 加载代码(servlet中):
import javax.servlet.servletconfig;
import javax.servlet.servletexception;
import javax.servlet.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.nio.charset.standardcharsets;
import java.util.properties;
@webservlet("/configloader")
public class servletconfigloader extends httpservlet {
private properties props;
// 初始化时加载配置(servlet生命周期)
@override
public void init(servletconfig config) throws servletexception {
super.init(config);
props = new properties();
// 通过servletcontext获取资源流,路径以"/"开头(基准为web应用根目录)
string resourcepath = "/web-inf/config/config.properties";
try (inputstreamreader isr = new inputstreamreader(
getservletcontext().getresourceasstream(resourcepath),
standardcharsets.utf_8)) {
props.load(isr);
} catch (ioexception e) {
throw new servletexception("web应用加载配置文件失败,路径:" + resourcepath, e);
}
}
@override
protected void doget(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {
resp.setcontenttype("text/plain;charset=utf-8");
// 读取配置并响应
string dburl = props.getproperty("db.url");
string systemname = props.getproperty("system.name");
resp.getwriter().write("web加载 - 数据库url:" + dburl + "\n");
resp.getwriter().write("web加载 - 系统名称:" + systemname);
}
}路径规则
- 路径以
/开头:基准目录为web应用根目录(如tomcat的webapps/应用名/) - 示例路径:
/web-inf/config.properties:web-inf目录下的配置文件/resources/config.properties:web应用根目录下的resources文件夹
- 禁止写绝对路径,仅支持web应用内的相对路径
优缺点
- 优点:安全(
web-inf目录不暴露给客户端)、适配web应用目录结构 - 缺点:仅支持web应用、依赖servlet容器、非web项目无法使用
三、六种加载方式对比总结
| 加载方式 | 适用场景 | 核心优点 | 核心缺点 |
|---|---|---|---|
| classloader.getresourceasstream() | 普通java项目、spring boot项目 | 跨环境移植性强、支持jar内资源、无需路径依赖 | 仅加载classpath下文件 |
| fileinputstream | 外部配置文件、动态指定路径 | 可加载任意位置文件、路径灵活 | 移植性差、需手动处理路径正确性 |
| spring框架(@propertysource) | spring生态项目 | 支持di注入、占位符解析、多文件加载 | 依赖spring框架 |
| java 9+ module加载 | 模块化项目(java 9+) | 资源访问可控、符合模块化规范 | 仅支持java 9+、需配置module-info.java |
| apache commons configuration | 需高级配置特性(多格式、刷新) | api简洁、功能强大、自动处理编码 | 需引入第三方依赖 |
| servletcontext.getresourceasstream() | web应用 | 安全(web-inf)、适配web目录结构 | 仅支持web应用、依赖servlet容器 |
四、最佳实践
1. 配置文件存放位置
- 普通java项目:
src/main/resources(classpath根目录),子目录按功能划分(如resources/config/db.properties) - web应用:
web-inf/config(避免客户端直接访问) - 外部配置:生产环境建议放在服务器独立目录(如
/opt/config),通过环境变量或命令行参数指定路径
2. 编码处理规范
- 强制指定utf-8编码:使用
inputstreamreader(原生api)或框架自带的编码配置(spring、commons configuration),避免中文乱码 - 禁止在properties文件中直接写中文(即使指定utf-8,部分工具可能不兼容),推荐使用unicode编码(如
system.name=\u6d4b\u8bd5\u7cfb\u7edf)
3. 路径写法规范
- 优先使用
classpath:前缀(spring项目)或相对classpath路径(classloader方式),避免绝对路径 - 多环境适配:通过环境变量(如
${config_path})或配置中心(nacos、apollo)管理路径,避免硬编码
4. 避免硬编码
- 禁止在代码中写死配置文件路径(如
"d:/config.properties"),通过命令行参数、环境变量、spring profiles等方式动态指定 - 示例(spring boot多环境):
# application-dev.properties(开发环境) config.path=classpath:config-dev.properties # application-prod.properties(生产环境) config.path=file:/opt/config/config-prod.properties
5. 配置刷新机制
- 静态配置:加载一次即可(如数据库连接参数)
- 动态配置:需支持刷新(如通过apache commons configuration的
refresh()方法,或配置中心推送更新)
五、常见问题排查
| 问题现象 | 根因分析 | 解决方案 |
|---|---|---|
| 中文乱码 | 未指定utf-8编码,默认iso-8859-1不支持中文 | 使用inputstreamreader指定utf-8,或框架编码配置 |
| 找不到配置文件(filenotfoundexception) | 路径错误(绝对路径不存在、相对路径基准错误) | 检查路径正确性、使用绝对路径测试、打印system.getproperty("user.dir")确认基准目录 |
| classloader加载不到文件 | 文件未放在classpath下、路径写绝对路径 | 移至src/main/resources、使用相对classpath路径 |
| spring @value注入为null | 未加@propertysource、配置文件路径错误、未扫描组件 | 检查注解配置、路径正确性、@component扫描范围 |
| 模块化项目加载失败 | 模块未开放资源访问权限 | 在module-info.java中添加opens 包名 to 模块名 |
六、总结
java加载properties文件的六种方式各有适配场景,核心选择原则:
- 普通java项目/ spring boot项目:优先使用
classloader.getresourceasstream()或spring的@propertysource - 外部配置文件/动态路径:使用
fileinputstream或命令行参数+classpath混合方式 - web应用:使用
servletcontext.getresourceasstream() - java 9+模块化项目:使用
module.getresourceasstream() - 需高级特性:使用apache commons configuration
实际开发中,需结合项目类型(普通java、spring、web、模块化)、配置存放位置(classpath内/外)、功能需求(动态刷新、多环境)选择合适的加载方式,并遵循编码规范、路径规范、避免硬编码等最佳实践,确保配置加载的可靠性和可维护性。
到此这篇关于java加载properties文件的六种方式:从基础到实战全解析的文章就介绍到这了,更多相关java加载properties文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论