JAVA读取properties配置文件

读取properties文件配置  (读取src下的配置文件,非resources目录下的)

package demo;
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
 
/**
 *	Properties配置文件处理工具
 * @author wdy
 */
public class PropertiesUtil {
    // 静态块中不能有非静态属性,所以加static
    private static Properties prop = null;
 
    //静态块中的内容会在类别加载的时候先被执行
    static {
        try {
            prop = new Properties();
            // prop.load(new FileInputStream(new File("C:\\jdbc.properties")));
            prop.load(PropertiesUtil.class.getClassLoader().getResourceAsStream("config.properties"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    //静态方法可以被类名直接调用
    public static String getValue(String key) {
        return prop.getProperty(key);
    }
    
    
    
    //测试
    public static void main(String[] args) {
    	String driver = PropertiesUtil.getValue("outLogin");
    	System.out.println(driver);
	}
    
    
}

测试结果:

 

然而问题来了,resources目录下的配置文件如何读取呢?因为resources目录下的文件是受保护的,所以不能直接访问

我们可以通过配置文件进行操作

一、配置:applicationContext.xml  扫描所有的配置文件、指定配置文件的地址

<context:property-placeholder location="classpath:config/**.properties" />
	
	<!-- 指定配置系统内路径的配置文件地址 -->
	<util:properties id="config" location="classpath:config/address/urladdress.properties"></util:properties>
	
	<!-- 整合用户权限平台的IP地址 -->
	<util:properties id="redis_config" location="classpath:config/address/redis.properties"></util:properties>

 

二、将其注入到类中

@Value("#{redis_config['redis.ip']}")
	private String ip;
	
	@Value("#{redis_config['redis.port']}")
	private Integer port;
	
	@Value("#{redis_config['redis.outTime']}")
	private Integer outTime;
	
	@Value("#{redis_config['redis.pwd']}")
	private String pwd;
	

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public Integer getPort() {
		return port;
	}

	public void setPort(Integer port) {
		this.port = port;
	}

	public Integer getOutTime() {
		return outTime;
	}

	public void setOutTime(Integer outTime) {
		this.outTime = outTime;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}


//使用的时候直接用就可以了
//例如  JedisPool jedisPool = new JedisPool(config, ip, port, outTime, pwd, 0);

需要说明的是:applicationContext.xml  util标签中的id跟类中的注解@Value("#{redis_config['redis.ip']}")是一致的

配置文件:redis.properties

#平台整合 redis 数据配置
redis.ip=192.168.142.104

#redis端口
redis.port=6666

#连接超时时间
redis.outTime=5000

#密码
redis.pwd=123456

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值