Java全局参数案例如何封装

wen java案例 30

本文目录导读:

Java全局参数案例如何封装

  1. 使用枚举单例模式(推荐)
  2. 使用Spring @ConfigurationProperties(Spring Boot项目推荐)
  3. 使用建造者模式构建不可变配置
  4. 线程安全的全局配置(高并发场景)
  5. 使用Properties文件加载配置
  6. 推荐使用场景
  7. 最佳实践建议

在Java中封装全局参数(配置参数)有多种方式,我来分享几个最佳实践案例:

使用枚举单例模式(推荐)

/**
 * 全局配置参数 - 枚举单例模式
 */
public enum GlobalConfig {
    INSTANCE;
    // 数据库配置
    private String dbUrl;
    private String dbUsername;
    private String dbPassword;
    // 系统配置
    private String systemName;
    private String version;
    private int maxConnections;
    // 缓存配置
    private long cacheTimeout;
    private boolean cacheEnabled;
    /**
     * 初始化配置
     */
    public void init(Properties props) {
        this.dbUrl = props.getProperty("db.url");
        this.dbUsername = props.getProperty("db.username");
        this.dbPassword = props.getProperty("db.password");
        this.systemName = props.getProperty("system.name", "DefaultSystem");
        this.version = props.getProperty("system.version", "1.0.0");
        this.maxConnections = Integer.parseInt(
            props.getProperty("system.maxConnections", "100")
        );
        this.cacheTimeout = Long.parseLong(
            props.getProperty("cache.timeout", "3600000")
        );
        this.cacheEnabled = Boolean.parseBoolean(
            props.getProperty("cache.enabled", "true")
        );
    }
    // Getter方法
    public String getDbUrl() { return dbUrl; }
    public String getDbUsername() { return dbUsername; }
    public String getDbPassword() { return dbPassword; }
    public String getSystemName() { return systemName; }
    public String getVersion() { return version; }
    public int getMaxConnections() { return maxConnections; }
    public long getCacheTimeout() { return cacheTimeout; }
    public boolean isCacheEnabled() { return cacheEnabled; }
    public static GlobalConfig getInstance() {
        return INSTANCE;
    }
}
// 使用示例
public class Application {
    public static void main(String[] args) {
        Properties props = new Properties();
        props.setProperty("db.url", "jdbc:mysql://localhost:3306/mydb");
        props.setProperty("db.username", "root");
        GlobalConfig.getInstance().init(props);
        // 获取配置
        String dbUrl = GlobalConfig.getInstance().getDbUrl();
        System.out.println("数据库URL: " + dbUrl);
    }
}

使用Spring @ConfigurationProperties(Spring Boot项目推荐)

/**
 * 配置属性类 - 自动绑定配置文件
 */
@Component
@ConfigurationProperties(prefix = "app.system")
public class SystemConfig {
    private String name;
    private String version;
    private int maxConnections;
    // 数据库配置
    private Database database = new Database();
    // 缓存配置
    private Cache cache = new Cache();
    // Getter和Setter
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getVersion() { return version; }
    public void setVersion(String version) { this.version = version; }
    public int getMaxConnections() { return maxConnections; }
    public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; }
    public Database getDatabase() { return database; }
    public void setDatabase(Database database) { this.database = database; }
    public Cache getCache() { return cache; }
    public void setCache(Cache cache) { this.cache = cache; }
    // 内部类 - 数据库配置
    public static class Database {
        private String url;
        private String username;
        private String password;
        private int poolSize = 10;
        // Getter和Setter
        public String getUrl() { return url; }
        public void setUrl(String url) { this.url = url; }
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
        public int getPoolSize() { return poolSize; }
        public void setPoolSize(int poolSize) { this.poolSize = poolSize; }
    }
    // 内部类 - 缓存配置
    public static class Cache {
        private boolean enabled = true;
        private long timeout = 3600000;
        private int maxSize = 1000;
        // Getter和Setter
        public boolean isEnabled() { return enabled; }
        public void setEnabled(boolean enabled) { this.enabled = enabled; }
        public long getTimeout() { return timeout; }
        public void setTimeout(long timeout) { this.timeout = timeout; }
        public int getMaxSize() { return maxSize; }
        public void setMaxSize(int maxSize) { this.maxSize = maxSize; }
    }
}
// application.yml配置
/*
app:
  system:
    name: MyApp
    version: 2.0.0
    max-connections: 100
    database:
      url: jdbc:mysql://localhost:3306/mydb
      username: admin
      password: ${DB_PASSWORD}
      pool-size: 20
    cache:
      enabled: true
      timeout: 7200000
      max-size: 5000
*/
// 使用示例
@Service
public class ConfigService {
    @Autowired
    private SystemConfig systemConfig;
    public void printConfig() {
        System.out.println("应用名称: " + systemConfig.getName());
        System.out.println("版本: " + systemConfig.getVersion());
        System.out.println("数据库URL: " + systemConfig.getDatabase().getUrl());
        System.out.println("缓存启用: " + systemConfig.getCache().isEnabled());
    }
}

使用建造者模式构建不可变配置

/**
 * 不可变全局配置 - 建造者模式
 */
public final class ImmutableGlobalConfig {
    private final String dbUrl;
    private final String dbUsername;
    private final int maxConnections;
    private final boolean cacheEnabled;
    private final long cacheTimeout;
    private ImmutableGlobalConfig(Builder builder) {
        this.dbUrl = builder.dbUrl;
        this.dbUsername = builder.dbUsername;
        this.maxConnections = builder.maxConnections;
        this.cacheEnabled = builder.cacheEnabled;
        this.cacheTimeout = builder.cacheTimeout;
    }
    // 只提供Getter方法
    public String getDbUrl() { return dbUrl; }
    public String getDbUsername() { return dbUsername; }
    public int getMaxConnections() { return maxConnections; }
    public boolean isCacheEnabled() { return cacheEnabled; }
    public long getCacheTimeout() { return cacheTimeout; }
    // 建造者类
    public static class Builder {
        private String dbUrl;
        private String dbUsername;
        private int maxConnections = 100;
        private boolean cacheEnabled = true;
        private long cacheTimeout = 3600000;
        public Builder dbUrl(String dbUrl) {
            this.dbUrl = dbUrl;
            return this;
        }
        public Builder dbUsername(String dbUsername) {
            this.dbUsername = dbUsername;
            return this;
        }
        public Builder maxConnections(int maxConnections) {
            this.maxConnections = maxConnections;
            return this;
        }
        public Builder cacheEnabled(boolean cacheEnabled) {
            this.cacheEnabled = cacheEnabled;
            return this;
        }
        public Builder cacheTimeout(long cacheTimeout) {
            this.cacheTimeout = cacheTimeout;
            return this;
        }
        public ImmutableGlobalConfig build() {
            if (dbUrl == null || dbUrl.isEmpty()) {
                throw new IllegalArgumentException("数据库URL不能为空");
            }
            if (dbUsername == null || dbUsername.isEmpty()) {
                throw new IllegalArgumentException("数据库用户名不能为空");
            }
            return new ImmutableGlobalConfig(this);
        }
    }
}
// 使用示例
public class Application {
    public static void main(String[] args) {
        ImmutableGlobalConfig config = new ImmutableGlobalConfig.Builder()
            .dbUrl("jdbc:mysql://localhost:3306/mydb")
            .dbUsername("root")
            .maxConnections(200)
            .cacheEnabled(true)
            .cacheTimeout(7200000)
            .build();
        System.out.println("数据库URL: " + config.getDbUrl());
        System.out.println("最大连接数: " + config.getMaxConnections());
    }
}

线程安全的全局配置(高并发场景)

/**
 * 线程安全的全局配置 - 使用ConcurrentHashMap和读写锁
 */
public class ThreadSafeGlobalConfig {
    private static volatile ThreadSafeGlobalConfig instance;
    private final Map<String, Object> configMap = new ConcurrentHashMap<>();
    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
    private ThreadSafeGlobalConfig() {
        // 初始化默认配置
        loadDefaultConfig();
    }
    public static ThreadSafeGlobalConfig getInstance() {
        if (instance == null) {
            synchronized (ThreadSafeGlobalConfig.class) {
                if (instance == null) {
                    instance = new ThreadSafeGlobalConfig();
                }
            }
        }
        return instance;
    }
    private void loadDefaultConfig() {
        configMap.put("system.name", "DefaultSystem");
        configMap.put("system.version", "1.0.0");
        configMap.put("db.pool.size", 10);
        configMap.put("cache.enabled", true);
    }
    // 读取配置
    public <T> T getConfig(String key, Class<T> type) {
        rwLock.readLock().lock();
        try {
            Object value = configMap.get(key);
            if (value == null) {
                return null;
            }
            return type.cast(value);
        } finally {
            rwLock.readLock().unlock();
        }
    }
    // 更新配置
    public <T> void updateConfig(String key, T value) {
        rwLock.writeLock().lock();
        try {
            configMap.put(key, value);
        } finally {
            rwLock.writeLock().unlock();
        }
    }
    // 批量更新配置
    public void batchUpdate(Map<String, Object> configs) {
        rwLock.writeLock().lock();
        try {
            configMap.putAll(configs);
        } finally {
            rwLock.writeLock().unlock();
        }
    }
    // 获取所有配置
    public Map<String, Object> getAllConfig() {
        rwLock.readLock().lock();
        try {
            return new HashMap<>(configMap);
        } finally {
            rwLock.readLock().unlock();
        }
    }
}
// 使用示例
public class Application {
    public static void main(String[] args) {
        ThreadSafeGlobalConfig config = ThreadSafeGlobalConfig.getInstance();
        // 读取配置
        String systemName = config.getConfig("system.name", String.class);
        Integer poolSize = config.getConfig("db.pool.size", Integer.class);
        Boolean cacheEnabled = config.getConfig("cache.enabled", Boolean.class);
        System.out.println("系统名称: " + systemName);
        // 更新配置
        config.updateConfig("db.pool.size", 20);
        // 批量更新
        Map<String, Object> newConfigs = new HashMap<>();
        newConfigs.put("cache.timeout", 7200000);
        newConfigs.put("max.connections", 200);
        config.batchUpdate(newConfigs);
    }
}

使用Properties文件加载配置

/**
 * 配置文件加载器
 */
public class ConfigLoader {
    private static final Logger logger = LoggerFactory.getLogger(ConfigLoader.class);
    private static Properties properties = new Properties();
    static {
        loadConfig("application.properties");
    }
    /**
     * 加载配置文件
     */
    public static void loadConfig(String fileName) {
        try (InputStream input = ConfigLoader.class.getClassLoader()
                .getResourceAsStream(fileName)) {
            if (input == null) {
                logger.warn("配置文件 {} 未找到", fileName);
                return;
            }
            properties.load(input);
            logger.info("成功加载配置文件: {}", fileName);
        } catch (IOException e) {
            logger.error("加载配置文件失败: {}", fileName, e);
            throw new RuntimeException("配置加载失败", e);
        }
    }
    // 获取字符串配置
    public static String getString(String key) {
        return properties.getProperty(key);
    }
    public static String getString(String key, String defaultValue) {
        return properties.getProperty(key, defaultValue);
    }
    // 获取整数配置
    public static int getInt(String key, int defaultValue) {
        String value = properties.getProperty(key);
        if (value == null) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            logger.error("配置 {} 的值 {} 不是有效的整数", key, value);
            return defaultValue;
        }
    }
    // 获取布尔配置
    public static boolean getBoolean(String key, boolean defaultValue) {
        String value = properties.getProperty(key);
        if (value == null) {
            return defaultValue;
        }
        return Boolean.parseBoolean(value);
    }
    // 获取所有配置
    public static Map<String, String> getAllConfig() {
        Map<String, String> configMap = new HashMap<>();
        for (String key : properties.stringPropertyNames()) {
            configMap.put(key, properties.getProperty(key));
        }
        return configMap;
    }
}
// application.properties配置
/*
system.name=MyApp
system.version=2.0.0
db.url=jdbc:mysql://localhost:3306/mydb
db.username=root
db.password=123456
cache.enabled=true
cache.timeout=3600000
*/
// 使用示例
public class Application {
    public static void main(String[] args) {
        String dbUrl = ConfigLoader.getString("db.url");
        int timeout = ConfigLoader.getInt("cache.timeout", 3600000);
        boolean cacheEnabled = ConfigLoader.getBoolean("cache.enabled", true);
        System.out.println("数据库URL: " + dbUrl);
        System.out.println("缓存超时: " + timeout);
    }
}

推荐使用场景

  1. 小型项目:使用枚举单例模式,简单高效
  2. Spring Boot项目:使用@ConfigurationProperties,自动注入
  3. 需要不可变配置:使用建造者模式
  4. 高并发场景:使用线程安全的ConcurrentHashMap实现
  5. 传统Java项目:使用Properties文件加载器

最佳实践建议

  1. 配置集中管理:所有配置集中在统一的位置
  2. 提供默认值:避免空指针异常
  3. 类型安全:避免字符串拼接导致的类型错误
  4. 支持热更新:对于需要动态修改的配置,提供更新接口
  5. 日志记录:记录配置加载和变更的日志
  6. 配置校验:加载配置时进行必要的校验

选择合适的封装方式取决于项目规模、框架选择和使用场景。

抱歉,评论功能暂时关闭!