java 写property文件_java读取properties文件的几种方式

方式一

1、编写PropertyUtil如下,可以读取处于任何位置的properties文件

public class PropertyUtil{

public static Properties getConfig(String path){

Properties props=null;

try{

props = new Properties();

InputStream in = PropertyUtil.class.getResourceAsStream(path);

BufferedReader bf = new BufferedReader(new InputStreamReader(in));

props.load(bf);

in.close();

}catch(Exception ex){

ex.printStackTrace();

}

return props;

}

}

2、在需要用到的地方以常量方式注入,例如下:

public class Configure {

public static Properties prop = PropertyUtil.getConfig("/epay.properties");

private String key;

public String getKey(){

return prop.getProperty("key");

}

}

方式二

@Component

@PropertySource("classpath:epay.properties")

public class Configure {

@Value("${appid}")

private String appid;

@Value("${key}")

private String key;

}

方式三

1、写PropertyUtil如下:

public final class PropertiesUtil extends PropertyPlaceholderConfigurer {

private static Map ctxPropertiesMap;

@Override

protected void loadProperties(Properties props) throws IOException {

super.loadProperties(props);

ctxPropertiesMap = new HashMap();

for (Object key : props.keySet()) {

String keyStr = key.toString();

String value = props.getProperty(keyStr);

ctxPropertiesMap.put(keyStr, value);

}

}

public static String getString(String key) {

try {

return ctxPropertiesMap.get(key);

} catch (MissingResourceException e) {

return null;

}

}

}

2、在spring-context.xml配置,list里可配置多个

classpath:epay.properties

三种方式对比总结:

就代码量和耦合程度来看,方式二最佳

方式三相对灵活,如果一个配置文件在多个类中用到,不需要每个类都注入一次,但需要在xml配置

-方式一和三相比,读取properties的方式不同而已,灵活程度是差不多的

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值