使用properties配置文件

1.读取配置文件,配置文件的命名需与类名相同,也可以写死,但要与类在同一目录下
这里写图片描述

public class MyProperties extends Properties {
    private static final long serialVersionUID = -2189089546796878893L;



    public MyProperties(@SuppressWarnings("rawtypes") Class clazz) throws IOException {
        String invokeClassShortName = clazz.getSimpleName();
        String propertiesFileName = invokeClassShortName + ".properties";
        InputStreamReader reader = new InputStreamReader(clazz.getResourceAsStream(propertiesFileName));
        this.load(reader);
    }

    public String getString(String key) {
        Object obj = getProperty(key);
        return (String)obj;
    }
}

2抽象类 调用方继承该抽象类

public abstract class PropertiesUtils4Test {
    protected MyProperties rb;

    public PropertiesUtil(){
        String className = this.getClass().getName();
        try {
            rb = new MyProperties(getClass());
        } catch (Exception mre) {
            System.out.println("No resource bundle found for: " + className);
        }
    }
    //利用java反射原理,将配置文件的值复制到对象中
    protected void populate()  {
        if (rb == null) return ;

        try {
        BeanUtils.copyProperties(this, rb);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

3.`使用时继承PropertiesUtil 类
public class TestProperies extends PropertiesUtils4Test {

@Test
public void testStart() throws Exception
{
    String id= rb.getString("flowNoForCommit");
    System.out.println(id);

    testEntity t = new testEntity();
    t.load();
    System.out.println(t.toString());
} 

}

4.测试用java反射的实体类

public class testEntity extends PropertiesUtils4Test{

    public String productNoForInit;

    public String getProductNoForInit() {
        return productNoForInit;
    }

    public void setProductNoForInit(String productNoForInit) {
        this.productNoForInit = productNoForInit;
    }

    @Override
    public String toString() {
        return "testEntity [productNoForInit=" + productNoForInit + "]";
    }

    public void load() {
        super.populate();
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值