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<String, String> ctxPropertiesMap;

    @Override
    protected void loadProperties(Properties props) throws IOException {
        super.loadProperties(props);
        ctxPropertiesMap = new HashMap<String, String>();
        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里可配置多个

<bean class="com.latech.utils.PropertiesUtil">
        <property name="locations">
            <list>
                <value>classpath:epay.properties</value>
            </list>
        </property>
    </bean>

三种方式对比总结:

  • 就代码量和耦合程度来看,方式二最佳
  • 方式三相对灵活,如果一个配置文件在多个类中用到,不需要每个类都注入一次,但需要在xml配置
    -方式一和三相比,读取properties的方式不同而已,灵活程度是差不多的
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,948评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,958评论 6 342
  • 一、Java jdk读取Properties配置文件 1、通过jdk提供的java.util.Properties...
    天下无忧2000阅读 9,736评论 0 1
  • 梵音共舞飞檐雪, 炉茗缭绕门前松。 山寺不见香缘客, 何妨重林寻旧踪。
    小红帽_8c52阅读 286评论 0 2
  • 今年我60岁,经历过大风大浪的我,尤其是伴随了自己将近40年的抑郁,很庆幸自己仍然持有一颗好奇的心、仍然从心里无比...
    婉言1228阅读 379评论 5 0