Java 配置方法

FreeGuideOnline 最新 2026-07-16

properties

应用配置

app.name=MyJavaApp app.version=1.0.0

数据库配置

db.url=jdbc:mysql://localhost:3306/mydb db.username=root db.password=secret


### 读取 Properties 文件

使用 `java.util.Properties` 类加载和读取属性:

```java
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesReader {
    private Properties properties = new Properties();

    public PropertiesReader(String fileName) {
        try (InputStream input = getClass().getClassLoader().getResourceAsStream(fileName)) {
            if (input == null) {
                System.out.println("抱歉,没有找到 " + fileName);
                return;
            }
            properties.load(input);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public String getProperty(String key) {
        return properties.getProperty(key);
    }

    public static void main(String[] args) {
        PropertiesReader reader = new PropertiesReader("config.properties");
        System.out.println("应用名称: " + reader.getProperty("app.name"));
        System.out.println("数据库地址: " + reader.getProperty("db.url"));
    }
}

带默认值的读取

避免因缺少配置而引起空指针异常,可使用 getProperty 的重载方法指定默认值:

String host = properties.getProperty("server.host", "localhost");
int port = Integer.parseInt(properties.getProperty("server.port", "8080"));

使用 XML 配置文件

XML 具有层次化结构,适合描述复杂的配置对象。虽然现在许多项目转向更轻量级的格式,但掌握 XML 配置仍对理解旧系统很有帮助。

简单的 XML 配置文件

创建 config.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <app>
        <name>MyJavaApp</name>
        <version>1.0.0</version>
    </app>
    <database>
        <url>jdbc:mysql://localhost:3306/mydb</url>
        <username>root</username>
        <password>secret</password>
    </database>
</configuration>

使用 DOM 解析器读取 XML

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.InputStream;

public class XMLConfigReader {
    public static void main(String[] args) throws Exception {
        InputStream input = XMLConfigReader.class.getClassLoader().getResourceAsStream("config.xml");
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(input);
        
        String appName = doc.getElementsByTagName("name").item(0).getTextContent();
        String dbUrl = doc.getElementsByTagName("url").item(0).getTextContent();
        
        System.out.println("应用名称: " + appName);
        System.out.println("数据库地址: " + dbUrl);
    }
}

对于更复杂的场景,你也可以使用 JAXB 直接将 XML 映射为 Java 对象,或者使用第三方库如 XStream。

使用注解和纯 Java 配置

在 Spring 等框架中,经常通过注解和 @Configuration 类来定义配置。这种方式能够让配置类型安全、支持自动补全,并且便于单元测试。

基础注解配置示例

import org.springframework.context.annotation.*;

@Configuration
@PropertySource("classpath:config.properties")
public class AppConfig {
    
    @Value("${db.url}")
    private String dbUrl;

    @Value("${db.username}")
    private String username;

    @Value("${db.password}")
    private String password;

    @Bean
    public DataSource dataSource() {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(dbUrl);
        config.setUsername(username);
        config.setPassword(password);
        return new HikariDataSource(config);
    }
}

通过 @Value 注解,属性值从 .properties 文件中注入对应的字段或方法参数中。这种方式把配置的读取和使用全部收敛在配置类中,清晰明了。

环境变量与系统属性

在生产环境中,敏感信息(如密码)不应该随代码一起提交。这时可以借助系统环境变量或 Java 系统属性。

读取环境变量

String dbPassword = System.getenv("DB_PASSWORD");
if (dbPassword == null) {
    dbPassword = "default_password";
}

读取 Java 系统属性

Java 启动时可通过 -D 参数设置系统属性:

java -Dapp.env=production -jar myapp.jar

然后在代码中读取:

String env = System.getProperty("app.env", "development");

这种方式特别适合与容器化环境结合,通过 Kubernetes ConfigMap 或 Docker 环境变量获得配置。

命令行参数解析

对于命令行工具,直接通过 main 方法的 args 传递配置参数也是常见做法。

简单的手动解析

public class CliApp {
    public static void main(String[] args) {
        for (String arg : args) {
            if (arg.startsWith("--port=")) {
                String port = arg.split("=")[1];
                System.out.println("端口: " + port);
            }
        }
    }
}

使用 JCommander 或 Picocli

更专业的做法是使用命令行解析库,例如 Picocli:

import picocli.CommandLine;
import picocli.CommandLine.Option;
import java.util.concurrent.Callable;

class MyApp implements Callable<Integer> {
    @Option(names = "--port", description = "服务端口")
    private int port = 8080;

    @Override
    public Integer call() {
        System.out.println("启动端口: " + port);
        return 0;
    }

    public static void main(String[] args) {
        int exitCode = new CommandLine(new MyApp()).execute(args);
        System.exit(exitCode);
    }
}

使用 YAML 配置文件

YAML 以更可读的方式表达层级结构,现今已成为许多现代 Java 项目的首选(如 Spring Boot 的 application.yml)。

添加依赖

如果你不在 Spring 环境中,可以使用 SnakeYAML 库解析 YAML 文件:

<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>2.0</version>
</dependency>

编写 YAML 文件

application.yml

app:
  name: MyJavaApp
  version: 1.0.0

database:
  url: jdbc:mysql://localhost:3306/mydb
  username: root
  password: secret

加载和读取 YAML

import org.yaml.snakeyaml.Yaml;
import java.io.InputStream;
import java.util.Map;

public class YamlConfigReader {
    public static void main(String[] args) {
        Yaml yaml = new Yaml();
        InputStream input = YamlConfigReader.class.getClassLoader()
                .getResourceAsStream("application.yml");
        Map<String, Object> data = yaml.load(input);
        
        Map<String, Object> app = (Map<String, Object>) data.get("app");
        Map<String, Object> db = (Map<String, Object>) data.get("database");
        
        System.out.println("应用名: " + app.get("name"));
        System.out.println("数据库 URL: " + db.get("url"));
    }
}