使用全局类通过加载properties文件,读取相关配置以实现代码的优化,以及维护的方便。

在java项目中,我们很多时候需要一些配置参数进行业务的处理、接口的调用等,比如腾讯企业邮箱,需要用的key等一些相对固定的参数,虽然参数不经常改变,但是如果需要改变的话,你需要一个个的去类里面寻找,大大影响维护速度以及效率。

因此,便写了一个全局类 Global以及资源文件加载类PropertiesLoader进行配置的读写。

PropertiesLoader资源文件加载类

package com.crawler.common.utils;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

/**
 * 资源文件加载类
 * @author siqiangming 2018年4月16日 下午3:43:26
 */
public class PropertiesLoader {
	protected static Log logger = LogFactory.getLog(PropertiesLoader.class);
	private static ResourceLoader resourceLoader = new DefaultResourceLoader();
	private final Properties properties;
	
	/**
	 * 构造函数,初始化对象的时候传递资源文件路径,并加载资源文件
	 * @param resourcesLocations
	 */
	public PropertiesLoader(String... resourcesLocations) {
		properties = loadProperties(resourcesLocations);
	}
	public Properties getProperties() {
		return properties;
	}
	/**
	 * 取出property,以系统property优先,如果系统没有,则去资源文件中取,取不到返回为空
	 * @author siqiangming 2018年4月17日 上午9:30:55
	 * @param key 属性名
	 * @return 属性值
	 */
	private String getValue(String key){
		logger.debug("获取value: " + key);
		String systemProperty = System.getProperty(key);
		if (systemProperty != null) {
			return systemProperty;
		}
		if (properties.containsKey(key)) {
			return properties.getProperty(key);
		}
		return "";
	}
	/**
	 * 取出property,取不到抛出异常
	 * @author siqiangming 2018年4月17日 上午9:35:42
	 * @param key 属性名
	 * @return 属性值
	 */
	public String getProperty(String key){
		logger.debug("获取property: " + key);
		String value = getValue(key);
		if (value == null) {
			throw new NoSuchElementException();
		}
		return value;
	}
	/**
	 * 取出property,取不到返回默认值
	 * @author siqiangming 2018年4月17日 上午9:38:06
	 * @param key 属性名
	 * @param defaultValue 默认值
	 * @return 属性值
	 */
	public String getProperty(String key, String defaultValue){
		String value = getValue(key);
		return value != null ? value : defaultValue;
	}
	/**
	 * 载入资源文件,文件路径使用spring resource格式
	 * @author siqiangming 2018年4月17日 上午9:24:46
	 * @param resourcesLocations 资源文件路径
	 * @return 资源属性集
	 */
	private Properties loadProperties(String... resourcesLocations) {
		Properties prop = new Properties();
		for (String location : resourcesLocations) {
			InputStream in = null;
			try {
				Resource resource = resourceLoader.getResource(location);
				in = resource.getInputStream();
				prop.load(in);
			} catch (IOException e) {
				logger.info("Could not load properties from path:" + location + ", " + e.getMessage());
			} finally {
				if(in != null){
					try {
						in.close();
					} catch (IOException e) {
						logger.info("Could not close InputStream: " + e.getMessage());
					}
				}
			}
		}
		return prop;
	}
}
Global全局类
package com.crawler.common.config;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.crawler.common.utils.PropertiesLoader;
import com.google.common.collect.Maps;

/**
 * 全局类
 * @author siqiangming 2018年4月17日 上午9:04:22
 */
public class Global{
	protected static Log logger = LogFactory.getLog(Global.class);
	/**
	 * 全局map
	 */
	private static Map<String, String> map = Maps.newHashMap();
	/**
	 * 资源文件加载器
	 */
	private static PropertiesLoader loader = new PropertiesLoader("crawler.properties");
	
	/**
	 * 获取配置,如果全局map中没有,获取后放入map
	 * @author siqiangming 2018年4月17日 上午9:41:23
	 * @param key 属性名
	 * @return 属性值
	 */
	public static String getConfig(String key){
		String value = map.get(key);
		if (value == null) {
			value = loader.getProperty(key);
			map.put(key, value != null ? value : "");
		}
		return value;
	}
}

现在我们只需要在资源文件中做下面的配置

##mysql database setting
jdbc.type=mysql
jdbc.driver=com.mysql.jdbc.Driver
#正式环境数据库地址
jdbc.url=jdbc:mysql://192.168.32.175:3306/crawler?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
#正式环境数据库密码
jdbc.password=***

#pool settings
jdbc.pool.init=1
jdbc.pool.minIdle=3
jdbc.pool.maxActive=20
#jdbc.testSql=SELECT 'x'
jdbc.testSql=SELECT 'x' FROM DUAL

##产品信息设置
productName=北京桃花岛爬虫工具
copyrightStartYear=2018
copyrightYear=2022
poweredBy=北京桃花岛信息技术有限公司
version=V1.0

##视图文件存放路径
web.view.prefix=/WEB-INF/views/
web.view.suffix=.jsp

##聚合数据配置
#识别图片验证码应用配置
juhe.appKey=****************************
juhe.codeType=1004
juhe.url=http://op.juhe.cn/vercode/index
juhe.connectTime=30000
juhe.socketTime=30000

现在我们可以用下面的方法直接读取配置了

	@Test
	public void getConfig(){
		String time = Global.getConfig("juhe.connectTime");
		System.out.println("time: "+time);
	}

结果

time: 30000


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1.1 前言 1.2 资料官网 1.3 spring boot起步之Hello World 1.4 Spring Boot返回json数据 1.5 Spring Boot热部署 1.6 Spring Boot使用别的json解析框架 1.7 全局异常捕捉 1.8 Spring Boot datasource - mysql 1.9 JPA - Hibernate 1.10 使用JPA保存数据 1.11 使用JdbcTemplate 1.12 Spring Boot修改端口号 1.13 Spring Boot配置ContextPath 1.14 Spring Boot改变JDK编译版本 1.15 处理静态资源(默认资源映射) 1.16 处理静态资源(自定义资源映射) 1.17 Spring Boot定时任务的使用 1.18 Spring Boot使用Druid和监控配置 1.19 Spring Boot使用Druid(编程注入) 1.20 Spring Boot普通调用bean 1.21 使用模板(thymeleaf-freemarker) 1.22 Spring Boot 添加JSP支持 1.23 Spring Boot Servlet 1.24 Spring Boot过滤器、监听器 1.25 Spring Boot 拦截器HandlerInterceptor 1.26 Spring Boot启动加载数据CommandLineRunner 1.27 Spring Boot环境变量读取和属性对象的绑定 1.28 Spring Boot使用自定义的properties 1.29 改变自动扫描的包 1.30 Spring Boot Junit单元测试 1.31 SpringBoot启动时的Banner设置 1.32 Spring boot 文件上传(多文件上传) 1.33 导入时如何定制spring-boot依赖项的版本 1.34 Spring Boot导入XML配置 1.35 Spring Boot使用@SpringBootApplication注解 1.36 Spring Boot 监控和管理生产环境 1.37 Spring Boot的启动器Starter详解 1.38 Spring Boot集成Redis实现缓存机制 1.39 Spring Boot Cache理论篇 1.40 Spring Boot集成EHCache实现缓存机制 1.41 Spring Boot分布式Session状态保存Redis 1.42 Spring Boot Shiro权限管理 1.43 Spring Boot Shiro权限管理 1.44 Spring Boot Shiro权限管理 1.45 Spring Boot Shiro权限管理

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值