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的方式不同而已,灵活程度是差不多的
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容