对JFinal的JFinalConfig的一次重构尝试。

本文介绍了如何在JFinal框架中优化配置管理,包括从多个properties文件读取配置并提供统一接口。通过新建PropertyConfig类,实现了配置参数的灵活读取和管理,支持多文件读取、兼容性读取以及单例模式运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一起因:

1)最近,有个小的工具需进行数据库操作,用到Jfinal的ActiveRecord,但是发现若要从配置文件中读取参数的,Jfinal中相应的代码都在JFinalConfig中。最后只能把相关的代码抽取出来来实现配置参数的读取。

2)一个基于Jfinal的项目中有不少配置参数,个人有个喜好,就是一个配置文件只干一件事情,比如database.properties里面只存取几个数据库连接信息。router.properties里面只存储路由相关信息。个人不喜欢将所有配置都塞到一个类似app.properties的文件里。

重构目标:

 

1)将从配置文件中读取参数相关代码从JFinalConfig中移除,专门建立一个类来做此事,方便单独需要ActiveRecord模块的场合使用,提高灵活性。

2)支持从多个properties文件中读取配置,并能通过统一的接口来获取这些文件中的所有配置信息。

上代码:

 

public abstract class JFinalConfig {

	/**
	 * Config constant
	 */
	public abstract void configConstant(Constants me);

	/**
	 * Config route
	 */
	public abstract void configRoute(Routes me);

	/**
	 * Config plugin
	 */
	public abstract void configPlugin(Plugins me);

	/**
	 * Config interceptor applied to all actions.
	 */
	public abstract void configInterceptor(Interceptors me);

	/**
	 * Config handler
	 */
	public abstract void configHandler(Handlers me);

	/**
	 * Call back after JFinal start
	 */
	public void afterJFinalStart(){};

	/**
	 * Call back before JFinal stop
	 */
	public void beforeJFinalStop(){};
}

 

 

新建的PropertyConfig类代码,

1)允许多文件读取
2)除了兼容JFianl从WEB-INF读取配置信息外,也允许从classpath中读取配置信息。
3)单例模式运行。

 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.jfinal.kit.PathKit;
import com.jfinal.kit.StringKit;

/**
 *
 * PropertyConfig: read properties file
 * file path: ../WEB-INFO/ or classpath
 *
 */
public class PropertyConfig {

	private ConcurrentMap<String, Object> properties =  new ConcurrentHashMap<String, Object>();

	private static PropertyConfig config = new PropertyConfig();

	private PropertyConfig(){}

	public static PropertyConfig me(){
		return config;
	}


	public void loadPropertyFile(String file){
		Properties property = new Properties();
		if (StringKit.isBlank(file))
			throw new IllegalArgumentException("Parameter of file can not be blank");
		if (file.contains(".."))
			throw new IllegalArgumentException("Parameter of file can not contains \"..\"");

		InputStream inputStream = null;
		String fullFile;	// String fullFile = PathUtil.getWebRootPath() + file;
		if (file.startsWith(File.separator))
			fullFile = PathKit.getWebRootPath() + File.separator + "WEB-INF" + file;
		else
			fullFile = PathKit.getWebRootPath() + File.separator + "WEB-INF" + File.separator + file;

		try {
			inputStream = new FileInputStream(new File(fullFile));
			property.load(inputStream);
		} catch (Exception eOne) {
            try {
            	ClassLoader loader = Thread.currentThread().getContextClassLoader();
            	property.load(loader.getResourceAsStream(file));
			} catch (IOException eTwo) {
				throw new IllegalArgumentException("Properties file loading failed: " + eTwo.getMessage());
			}
		}
		finally {
			try {if (inputStream != null) inputStream.close();} catch (IOException e) {e.printStackTrace();}
		}
		if (property != null){
			for(Entry<Object,Object>  entry : property.entrySet()){
				this.properties.put(entry.getKey().toString(), entry.getValue());
			}
		}
	}

	public String getProperty(String key) {
		if(this.properties.containsKey(key)){
			return properties.get(key).toString();
		}
		return null;
	}

	public String getProperty(String key, String defaultValue) {
		if(this.properties.containsKey(key)){
			return properties.get(key).toString();
		}
		return defaultValue;
	}

	public Integer getPropertyToInt(String key) {
		Integer resultInt = null;
		String resultStr = this.getProperty(key);
		if (resultStr != null)
			resultInt =  Integer.parseInt(resultStr);
		return resultInt;
	}

	public Integer getPropertyToInt(String key, Integer defaultValue) {
		Integer result = getPropertyToInt(key);
		return result != null ? result : defaultValue;
	}

	public Boolean getPropertyToBoolean(String key) {
		String resultStr = this.getProperty(key);
		Boolean resultBool = null;
		if (resultStr != null) {
			if (resultStr.trim().equalsIgnoreCase("true"))
				resultBool = true;
			else if (resultStr.trim().equalsIgnoreCase("false"))
				resultBool = false;
		}
		return resultBool;
	}

	public Boolean getPropertyToBoolean(String key, boolean defaultValue) {
		Boolean result = getPropertyToBoolean(key);
		return result != null ? result : defaultValue;
	}
}

使用例子:

 

 

public void configConstant(Constants me) {
		//加载数据库配置文件
		PropertyConfig.me().loadPropertyFile("database.properties");
		PropertyConfig.me().loadPropertyFile("app.properties");
               //设定为开发者模式
 me.setDevMode(PropertyConfig.me().getPropertyToBoolean("jfinal.devmode", false));

 

 

public void configPlugin(Plugins me) {
		//从配置文件中获取数据库配置项
		PropertyConfig config = PropertyConfig.me();
        String driver = config.getProperty("dataSource.driverClass");
        String jdbcUrl = config.getProperty("dataSource.url");
        String username = config.getProperty("dataSource.userName");
        String password = config.getProperty("dataSource.password");

 

打完收工。

转载于:https://my.oschina.net/myaniu/blog/144832

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值