java读取properties文件的几种方式

2018-08-02  本文已影响0人  夏日橘子冰

方式一

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>

三种方式对比总结:

上一篇下一篇

猜你喜欢

热点阅读