两种方式读取maven工程的properties配置文件

一、新建maven工程,并在resource文件夹下建立需要读取的配置文件(若新建的maven工程没有resource文件夹,则自己新建),例如systemConfig.properties



二、读取配置文件

      1.通过ResourceBundle类读取

import java.util.ResourceBundle;

public class ResourceUtil {
    private static final ResourceBundle resourceBundle;

    static{
        resourceBundle = ResourceBundle.getBundle("systemConfig");
    }

    public static String getKey(String key){
       return resourceBundle.getString(key);
    }
}

 2.通过properties读取

public class PropertiesTest {
        public static Properties confProperties;
        static {
            try {
                init();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public static void init() throws IOException {
            if (confProperties == null) {
                confProperties = new Properties();

                InputStream in = PropertiesTest.class.getClassLoader().getResourceAsStream("systemConfig.properties");

                try {
                    confProperties.load(in);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    in.close();
                }
            }
        }

        public static Properties getProperties() throws IOException {
            init();
            return confProperties;
        }

        public static void clear() {
            confProperties.clear();
            confProperties = null;
        }

        public static String get(String key) {
            try {
                init();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return confProperties.getProperty(key);
        }
}

注意:因为必须将项目跑起来才能读取properties,因此不能直接通过main方法测试

三、测试

因此我写了一个Controller



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值