从properties中读取配置创建对象

Posted lyn4ever

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从properties中读取配置创建对象相关的知识,希望对你有一定的参考价值。

主要做两个事,从properties配置文件中读取信息,通过反射创建对象

思路主要有两种,遍历得到的属性集合,然后设置类的属性

遍历类的属性集合,从配置文件中读取(不推荐,因为类的属性有多样化,会报错)

try {
   Properties prop = new Properties();
   prop.load(new FileInputStream(
     "F:\user.properties"));
   Class class1 = Class.forName("com.zlkj.config.User1");
   Object newInstance = class1.newInstance();
//这样就可以拿到本类中公有和私有方法
   Field[] fields = class1.getDeclaredFields();
   for (Field field : fields) {
    field.setAccessible(true);
    field.set(newInstance, prop.getProperty(field.getName()));
   }
   
   System.out.println(newInstance.toString());
  } catch (Exception e) {
   e.printStackTrace();
  }

以上方法要注意几点:

  • 注入的类的属性要是String类,如果是其他类,要调用相应的方法,不然会报错;
  • 有时候可能要拿父类的属性,调用 getSuperClass().getDeclaredFields()

    本文由博客一文多发平台 OpenWrite 发布!

以上是关于从properties中读取配置创建对象的主要内容,如果未能解决你的问题,请参考以下文章

读取配置文件

依赖注入之setter注入---只需修改配置,电脑就可以安装不同的打印机;读取properties配置文件并创建实例;实现不采用new的方式直接实例化对象

创建型-配置工厂

Java读取Properties配置文件

SpringBoot读取配置文件(从classpath/file读取yml/properties文件)

创建型-配置工厂